【问题标题】:Making a for loop wait WITHOUT a library in JS在 JS 中没有库的情况下进行 for 循环等待
【发布时间】:2016-08-22 10:32:15
【问题描述】:

如何创建一个for 循环,在没有库(如jQuery)的情况下开始循环的新迭代之前等待异步调用完成?

例子:

var items = [1,2,3,4,5];

for (var i = 0; i < items.length; i++) {

    var promise = new Promise(function(resolve, reject){
        asyncAPIcall({
            body : item[i]
        }, function(error, response){
            if(error) {
                reject();
            } else {
                resolve();
            }
        });

    promise.then(function() {
            //continue loop
        }, function() {
            //break loop
        });

}

谢谢


更新 (4/29)

我想到了这个解决方案,我在其中创建了一个调用自身的函数:

var items = [1,2,3,4,5];

var counter = items.length - 1; //minus one since array is zero based.

function myLoop(){

    asyncAPIcall({
        body : item[counter]
    }, function(error, response){
        if(error) {
            // Error message.
        } else {
            counter = counter - 1;
            if(counter == -1){
                //Done
            }
            else {
                myLoop();
            }
        }
    });

}

【问题讨论】:

  • 你不能。你真正需要做什么?
  • for 循环是同步的。它永远不能等待异步操作。你可以有一个队列或类似的东西。
  • @Amit 我需要触发一长串 API 调用,如果其中一个调用失败,则停止其他调用链。我正在与一次只接受一个对象的 API 进行交互,因此我必须点击它 20 次才能发送我的所有对象。
  • @FelixKling 有什么建议吗?

标签: javascript node.js for-loop asynchronous


【解决方案1】:

您可以使用 reduce 使它们按顺序处理(或使用常规 for 循环设置承诺链——我自己更喜欢 reduce)。

let promise = items.reduce((carry, current) => {
    return carry.then(arr => {
        return asyncAPIcall({ body: current }).then(result => arr.concat([ result ]));
    });
}, Promise.resolve([]));

promise.then(finalResult => {
    console.log('final result:', finalResult);
});

但是,如果您实际上不需要捕获这些承诺解决方案的结果,那么这可能超出您的需要。另请注意,您在它的末尾仍然会有一个 Promise,其中将包含每个 Promise 的结果数组,对应于它们的原始数组位置。

此外,这里是 asyncAPIcall 的模拟版本,如果您想跟踪调用方法的方式/位置,它应该有助于在此处显示操作顺序。

function asyncAPIcall(obj) {
    console.log('asyncAPIcall for:', obj);
    return new Promise((resolve) => {
        setTimeout(() => {
            let resolution = obj.body + 5; // change the value in some way, just to show that input !== output
            console.log('resolving with:', resolution);
            return resolve(resolution);
        }, 100);
    });
}

【讨论】:

  • 我试试看。谢谢推荐!
  • 祝你好运!如果您不需要最后的结果,那么许多阵列恶作剧可以完全消失。如果需要,我可以添加一个不关心结果的更简单的版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多