如何在 Node.js 中等待一个函数完成? [复制]

Posted

技术标签:

【中文标题】如何在 Node.js 中等待一个函数完成? [复制]【英文标题】:How to wait for a function to be done in Node.js? [duplicate] 【发布时间】:2016-05-31 09:47:06 【问题描述】:
var count = 0;
list.forEach(function(entry)
    var coll = db.collection(entry);
    coll.count(function(err,result)
       count = count + result;
    )
)

function(count)
//do something with count

我在 node.js 上使用 mongoDB 本机驱动程序,问题是应该在计算每个集合中的所有条目后使用 count 的函数会提前触发,这很明显,因为它是异步的.我已经搜索了很长一段时间的解决方案,但还没有找到任何东西。

【问题讨论】:

我确实只是在工作中做到了这一点。 mongo 模块是异步的,所以最好的方法是使用一个 Promise 库(或原生 Promise)。我建议 bluebird 或 async 【参考方案1】:

你可以使用承诺

Promise.all(
    list.map(function(entry)
        return new Promise(function(resolve, reject) 
            db.collection(entry).count(function(err, result)
                if (err) return reject(err);
                resolve(result);
            );
        );
    )
).then(count);

function count(result) 
    var sum = result.reduce(function(a,b)  return a + b );

【讨论】:

以上是关于如何在 Node.js 中等待一个函数完成? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何等待module.export函数完成请求,然后再将其返回值分配给不同JS文件中的变量[重复]

在 Node.js 中等待异步函数返回

Node.js 回调函数

Node.js 和 Redis;等待循环完成

等待异步函数完成而不添加回调

node js 回调函数