简体   繁体   English

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

[英]How to call a JavaScript function sequentially in a for loop?

I want to pass each item into a function that take times.我想将每个项目传递给一个需要时间的函数。 But seems that the JS function is asynchronized.但似乎JS功能是异步的。 How can I call the function sequentially ?如何按顺序调用该函数? (Pass next item to function after the previous done) (在上一个完成后将下一个项目传递给函数)

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

function doSomething(item) {
    // do something take time
}

My solution is call the function recusively.我的解决方案是递归调用该函数。 But I want to know is there a different way to solve this issue ?但我想知道有没有不同的方法来解决这个问题? Thanks.谢谢。

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

function doSomething(item, i) {
    // do something take time
    doSomething(myArray, i + 1);
}

In JavaScript, as of 2020, the for-loop is async/await aware.在 JavaScript 中,截至 2020 年,for 循环具有异步/等待感知能力。 You can return a promise and then await that promise inside of the for loop.您可以返回一个承诺,然后在 for 循环内await该承诺。 This causes the loop to execute in a series, even for long running operations.这会导致循环连续执行,即使是长时间运行的操作。

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

Read more about async await in for loops and forEach loops here https://zellwk.com/blog/async-await-in-loops/在此处阅读有关 for 循环和 forEach 循环中的异步等待的更多信息https://zellwk.com/blog/async-await-in-loops/

if you want to pass next item to function after the previous done, you can try to use promise, just like this如果你想在上一个完成后将下一个项目传递给函数,你可以尝试使用promise,就像这样

var Q = require('q'); 
var promise;
main();
function main() {
     promise = doSomethingPromise(0)
    for (var i = 1; i < 10 ; i++) {
        (function (i) {
            promise = promise.then(function (res) {
                return doSomethingPromise(res + ' ' + i)
            });
        })(i)

    }
}

function doSomethingPromise (item) {
   var d = Q.defer();
      d.resolve(doSomething(item));
   return d.promise;
}

function doSomething(item) {
    // do something take time
    console.log('doSomething', item);
    return item;
}

it can make you function to be called by order.它可以让您按顺序调用函数。

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

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