承诺循环 - 基本

时间:2017-04-13 11:35:32

标签: javascript node.js promise

循环使用此Promise链的最佳方式是什么?代码工作正常,没有'for循环',最后一步在MongoDB中保存JSON。第一次迭代后,NodeJS shell挂起。

for(i=0; i < 2; i++){
    forLoop(countOfFlights,jsonRead).then(function(fromResolve){
        return filter(fromResolve)
    }).then(function(fromResolve){
        return sort(fromResolve)
    }).then(function(fromResolve){
        saveMongoDB(fromResolve)
    })}

我查看了Promise&amp;的一些主题。循环,但这些例子对我来说太复杂了。也许只有一条神奇的线条可以解决它。我确信更好地了解它悬挂的原因也是有益的。

亲切的问候,

1 个答案:

答案 0 :(得分:0)

- 评论继续 - 你可以只迭代同步,但这总是比使用promises慢。只要文件插入与彼此无关,能够同时插入所有文件而无需等待查看prev插入是否成功,所以我个人坚持承诺。

我的目标是这样的结构:

// We want an array with promise objects.
// Since forLoop() returns a promise, we can call it twice
// I don't know if 'i' is used anywhere in your loop, so if you do need it,
// you can replace this with a loop that creates the arrays of promises.
var requests = [
    forLoop(countOfFlights,jsonRead), //
    forLoop(countOfFlights,jsonRead)
];
Promise.all(
    requests
 ).then(function( rawRes ) {
    return rawRes.map( filter );
}).then(function( filteredRes ) {
    return filteredRes.map( sort );
}).then(function( sortedRes ) {
    return sortedRes.map( saveMongoDB );
}).then(function( insertedRes ) {
    // Do something to check if the database inserts succeeded.
}).catch(function( errors ) {
    console.error( errors );
});

所以我的想法是首先使用循环来创建一堆promises,然后我们同时运行所有的promises,然后处理所有结果。

如果由于某种原因你确实想要单独处理每个文件,请将代码放入函数中并直接循环该函数而不是代码。这也意味着你需要某种计数器或者还需要promise.all()来检查所有文件插入的完成时间:

var insertFile = function insertFile( count, json ) {
        return forLoop(
                count,
                json 
              ).then(function(fromResolve){
                return filter(fromResolve);
            }).then(function(fromResolve){
                return sort(fromResolve);
            }).then(function(fromResolve){
                return saveMongoDB(fromResolve);
            }).then(function( inserted ) {
                // do stuff seperately for an insert
                return inserted;
            }).catch(function( error ) {
                throw error;
            });
        });
    },
    i,
    requests = [];

for (i = 0; i < 2; i += 1) {
    requests.push( insertFile( countOfFlights, jsonReads ) );
}
Promise.all(
    requests
 ).then(function( responses ) {
    // all files are inserted
}).catch(function( error ) {
    // something went wrong
});

您可以将过滤器和排序回调合并为一个.reduce(),但这只是一个侧面注释,因为我不知道.filter()和.sort()是如何编码的。