在继续循环后等待每个承诺完成

问题描述:

下面我有两个函数.其中一个返回一个承诺,我希望在每个循环中等待它先完成然后移动一个.正如您将在下面看到的,结果不是所需的/同步的.我应该不使用 async.forEachof

Below I have two functions. One of the returns a promise and I want in each and every loop to wait for it to finish first and then move one. As you'll see below the result is not the desired/synchronous. Should I not use async.forEachof

function test(num, callback)
{
    console.log("inside function: "+num)
    return new Promise((resolve, reject) => {
        my.promise(num).then(() => {
            console.log("done: "+num)
            resolve(callback);
        }).catch(e => console.error(e));
    }).catch(console.error);
}

function start_function()
{
    //stuff
    async.forEachOf(arr, function (itm, i, callback){
        console.log(i)
        test(i, callback).catch(e => console.error(e));
    }, function (err) {
        console.log("ALL DONE")
    });
}

结果:

0
inside function 0
1
inside function 1
2
inside function 2
done: 0
done: 2 //wrong should always be 1, finished before the previous promise.
done: 1 //wrong
ALL DONE

我不想使用 PromiseAll 不是因为我不想,而是因为我需要每个 Promise 等待前一个的结果,然后开始下一个.因此,将它们全部收集起来,然后等待它们按照我需要做的任何顺序完成是没有意义的.

I do not want to use PromiseAll not because I dont want but because I need each promise to wait for the previous one's result, and then start the next one. It is pointless therefore to gather them all and then wait for them to be done in whatever order and to what I need to do.

这个方法怎么样:

(function loopOnItems(i) {           

        dummyGoogleAPI.someAsyncMethod(data).then(function (_response) {                
            // do something with response          
        })
        .catch(function (error) {
            console.error(error);
        });

        if (--i){
            loopOnItems(i);    
        }//  decrement i and call loopOnItems again if i > 0
        else{
            _callback(errors);
        }            
})(count);

你有一些 count 并且我们调用 loopOnItems 方法直到 count > 0

You have some count and we call loopOnItems method till count > 0