如何在for循环中顺序调用JavaScript函数?

Aar*_*ron 4 javascript synchronization node.js

我想将每个项目传递到一个需要时间的函数中。但似乎JS功能是异步的。如何顺序调用该函数?(在上一项完成后将下一项传递给函数)

function main() {
    for (var i = 0; i < n ; i++) {
        doSomething(myArray[i]);
    }
}

function doSomething(item) {
    // do something take time
}
Run Code Online (Sandbox Code Playgroud)

我的解决方案是递归调用该函数。但我想知道是否有不同的方法来解决这个问题?谢谢。

function main() {
    doSomething(myArray, 0);
}

function doSomething(item, i) {
    // do something take time
    doSomething(myArray, i + 1);
}
Run Code Online (Sandbox Code Playgroud)

gtz*_*lla 6

在 JavaScript 中,截至 2020 年,for 循环是异步/等待感知的。您可以返回一个承诺,然后await在 for 循环内返回该承诺。这会导致循环连续执行,即使对于长时间运行的操作也是如此。

function randomSleep(ms, seed=10) {
    ms = ms * Math.random() * seed;
    return new Promise((resolve, reject)=>setTimeout(resolve, ms));
} 
async function doSomething(idx) {
  // long running operations
  const outcome = await randomSleep(500);
  return idx;
}   
const arrItems = ['a','b','c','d'];
for(let i=0,len=arrItems.length;i<len;i++) {
  const result = await doSomething(i);
  console.log("result is", result)
}
Run Code Online (Sandbox Code Playgroud)

在此处阅读有关 for 循环和 forEach 循环中的 async wait 的更多信息https://zellwk.com/blog/async-await-in-loops/