Javascript 何时在Node.js ES6中启动Promise中的代码?
我创建了一个方法,为数组中的每个元素创建承诺Javascript 何时在Node.js ES6中启动Promise中的代码?,javascript,node.js,ecmascript-6,promise,es6-promise,Javascript,Node.js,Ecmascript 6,Promise,Es6 Promise,我创建了一个方法,为数组中的每个元素创建承诺 queries.push(function (collection) { new Promise((resolve, reject) => { collection.find({}).limit(3).toArray(function (err, docs) { if (err) reject(err); resolve(docs); }); });
queries.push(function (collection) {
new Promise((resolve, reject) => {
collection.find({}).limit(3).toArray(function (err, docs) {
if (err) reject(err);
resolve(docs);
});
});
});
const getAnalyticsPromises = (collection) => {
let promises = [];
queries.each((item) => {
promises.push(item(collection));
});
console.log(queries);
return promises;
}
此代码返回以下错误:
(node:10464) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: queries.each is not a function
(node:10464) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
问题是:承诺何时兑现?当我创建它时:
promises.push(item(collection));
或者当我用then()函数调用它时?那么您的错误是关于
查询没有方法每个-您应该使用forEach
。
Bescides您应该从您的功能中返回承诺:
queries.push(function (collection) {
return new Promise((resolve, reject) => {
collection.find({}).limit(3).toArray(function (err, docs) {
if (err) reject(err);
resolve(docs);
});
});
});
因此,当您调用item(collection)
其中item
是您的匿名函数之一时,将创建承诺。
现在,您可以根据需要处理它,例如:
let p = item(collection);
p.then(...).catch(...)
您的错误是关于查询
没有方法每个
-您应该使用forEach
。
Bescides您应该从您的功能中返回承诺:
queries.push(function (collection) {
return new Promise((resolve, reject) => {
collection.find({}).limit(3).toArray(function (err, docs) {
if (err) reject(err);
resolve(docs);
});
});
});
因此,当您调用item(collection)
其中item
是您的匿名函数之一时,将创建承诺。
现在,您可以根据需要处理它,例如:
let p = item(collection);
p.then(...).catch(...)
哦,不,当然,非常感谢。现在我明白了什么时候打电话给你的承诺。哦,不,当然,谢谢你。现在我明白了什么时候叫承诺。