0

I have the following async function in Typescript, and it seems that await doesn't block and yield the required result as I expect.

async function getCroppedImgContent(origImgBuffer: Buffer) {
  console.log("Inside setCroppedImgContent");
  let croppedBuffer =  await sharp(origImgBuffer)
    .resize(4000, 4000)
    .max()
    .toBuffer();
  console.log("After crop");

  return croppedBuffer;
}

"After crop" is not print immediately after "Inside setCroppedImgContent", but a lot later. Looks like await is not working.

14
  • What is the problem? Commented Aug 12, 2017 at 17:41
  • Does sharp().resize().max().toBuffer() return a promise because await is only really useful when you are awaiting a promise. Commented Aug 12, 2017 at 17:43
  • The execution is not blocked at the await line, result is returned later Commented Aug 12, 2017 at 17:44
  • Yes, it returns Promise. I have checked it in debugger. Commented Aug 12, 2017 at 17:45
  • @jfriend00 yes, it does: https://github.com/lovell/sharp#examples Commented Aug 12, 2017 at 17:45

1 Answer 1

2

Nenad, the fact that you used await inside your function does not mean it will be executed synchronously. await just makes the execution be blocked for a single call.

If you want console.log("After setCroppedImgContent"); to be executed after getCroppedImgContent is completed you need to await its call:

await getCroppedImgContent(origContent)
    .then(function (croppedBuffer) {
    image.content = croppedBuffer;
    console.log("Set image content");
});
Sign up to request clarification or add additional context in comments.

4 Comments

But in this case this code should be added to a new function, and marked with async keyword.
What about "After crop", shouldn't it be printed after "Inside setCroppedImgContent" ? In my case it isn't, and that's my biggest problem. I have added the calling code because of the comments, but it's irrelevant.
Now you changed your description completely, and it seems what I would consider correct behaviour.
"After crop" is not printed immediately because the execution is blocked waiting for the Promise to be completed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.