[英]When start code in Promise in Node.js ES6?
我創建了一個方法,為數組中的每個元素創建一個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;
}
此代碼返回此錯誤:
(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()函數調用它時?
那么你有誤差約為queries
還沒有方法each
-你應該使用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(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.