[英]When start code in Promise in Node.js ES6?
I make a method that create a promise for each element in array. 我创建了一个方法,为数组中的每个元素创建一个promise。
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;
}
This code return this errors: 此代码返回此错误:
(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.
The question is: When the promise is called? 问题是:当承诺被召唤时? When i create it: 当我创建它:
promises.push(item(collection));
or when i call it with then() function? 或者当我用then()函数调用它时?
Well the error you have is about queries
has not method each
- you should use forEach
instead. 那么你有误差约为queries
还没有方法each
-你应该使用forEach
来代替。
Bescides you should return promise from your function: Bescides你应该从你的函数返回承诺:
queries.push(function (collection) {
return new Promise((resolve, reject) => {
collection.find({}).limit(3).toArray(function (err, docs) {
if (err) reject(err);
resolve(docs);
});
});
});
So when you call item(collection)
where item
is one of your anonymous functions, the promise would be created. 因此,当您调用item(collection)
, item
是您的匿名函数之一,将创建承诺。
And now you can handle with it whatever you need, for example: 现在,您可以随心所欲地处理它,例如:
let p = item(collection);
p.then(...).catch(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.