简体   繁体   English

打字稿异步等待不起作用

[英]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. 我在Typescript中具有以下异步函数,并且看来await不会阻塞并产生期望的结果。

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. 不是在“ Inside setCroppedImgContent”之后立即打印“ Afterrop”,而是要晚很多。 Looks like await is not working. 看起来等待不起作用。

Nenad, the fact that you used await inside your function does not mean it will be executed synchronously. 内纳德,您所使用的事实, await你的函数内部并不意味着它会被同步执行。 await just makes the execution be blocked for a single call. await只是使执行阻塞一次调用。

If you want console.log("After setCroppedImgContent"); 如果要console.log("After setCroppedImgContent"); to be executed after getCroppedImgContent is completed you need to await its call: 要在getCroppedImgContent完成后执行,您需要await其调用:

await getCroppedImgContent(origContent)
    .then(function (croppedBuffer) {
    image.content = croppedBuffer;
    console.log("Set image content");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM