Nenad
Nenad

Reputation: 494

Typescript async await not working

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.

Upvotes: 0

Views: 2003

Answers (1)

Thiago Barcala
Thiago Barcala

Reputation: 7353

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");
});

Upvotes: 2

Related Questions