typescript 如何在 Javascript 中的 array.forEach 中等待异步函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32389598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:05:03  来源:igfitidea点击:

How to Wait on Async function inside array.forEach in Javascript

javascripttypescript

提问by Govind Kalyankar

I am trying to make an asyncrequest within foreachto fetch data in order user it later but its not working for me.

我正在尝试在其中发出async请求foreach以获取数据以便稍后用户使用它,但它对我不起作用。

I know Array.Foreachis a synchronous function so I even tried $.when.done but still it does not wait until it finish.

我知道Array.Foreach是一个同步函数,所以我什至尝试了 $.when.done 但它仍然没有等到它完成。

I could have used callback if it was a single value but its an array . Is there a better way to handle this by callback to achieve waiting on asyncrequest before moving next?

如果它是单个值但它是一个数组,我可以使用回调。有没有更好的方法通过回调来处理这个问题,以实现async在下一步移动之前等待请求?

browseItems.forEach((browseItem: any) => {

   AsynchFunction();

   cosole.log("Step 2")  
}
function AsynchFunction(){
   console.log("Step 1")
}

I am trying to get an output like

我正在尝试获得类似的输出

Step 1

步骤1

Step 2

第2步

采纳答案by kennasoft

Once you start using async functions, you go either of two ways: callbacksor promises. In the case of the above code, you just need to define a callback function to be called after the async function returns. See sample below:

一旦开始使用异步函数,您可以选择以下两种方式之一:callbackspromises. 上面代码的情况,只需要定义一个回调函数,在async函数返回后调用即可。请参阅下面的示例:

browseItems.forEach((browseItem: any) => {
   AsynchFunction(postProcess);   
}
function AsynchFunction(callback){
   console.log("Step 1");
   if(asyncProcessDone){
       callback();
   }
}
function postProcess(){
    console.log("Step 2")
}

回答by Joe Skeen

Building on @basarat's answer, I found that this works quite well if you are using the async/awaitfeature in TypeScript (as of TS 1.7 requiring ES6 target):

@basarat 的回答为基础,我发现如果您async/await在 TypeScript中使用该功能(从 TS 1.7 开始需要 ES6 目标),这非常有效:

async function processData(data: any[]) {
  const promises = data.map(async (item) => {
    await doSomeAsyncStuff(item);
    //you can do other stuff with the `item` here
  });
  await Promise.all(promises);

  //you can continue with other code here that will execute after all the async code completes
}

async function doSomeAsyncStuff(value) {
  return new Promise((resolve, reject) => {
    //call some async library or do a setTimeout and resolve/reject the promise
  });
}

Update:asyncand awaitare now available for TypeScript code targeting ES5as well in the masterbranch of TypeScript, soon to be released as TypeScript 2.1. You can install it today using npm install --save-dev typescript@next

更新:asyncawait现在可用的打字稿代码瞄准ES5以及在master打字稿的分公司,即将推出的为打字稿2.1。您可以使用今天安装它npm install --save-dev typescript@next

Update:This feature is available for all ES targets in the current version of TypeScript. The one caveat I have noticed is that if you are targeting ES5 or ES3, you will need to provide a Promise polyfill or the code will fail on older browsers.

更新:此功能适用于当前版本的 TypeScript 中的所有 ES 目标。我注意到的一个警告是,如果您的目标是 ES5 或 ES3,则需要提供 Promise polyfill,否则代码将在旧浏览器上失败。

回答by basarat

Is there a better way to handle this by callback to achieve waiting on async req before moving next

有没有更好的方法通过回调来处理这个问题,以实现在移动下一步之前等待异步请求

If you are using promises you can use a function like Promise.all:

如果您正在使用承诺,您可以使用如下函数Promise.all

var promises = browseItems.map((browseItem: any) => AsynchFunction());
Promise.all(promises).then((values)=>{});