gpt4 book ai didi

javascript - Node.js ES6 中的 Promise 何时启动代码?

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:19 25 4
gpt4 key购买 nike

我创建了一个方法,为数组中的每个元素创建一个 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.

问题是:何时调用 Promise?当我创建它时:

promises.push(item(collection));

或者当我用 then() 函数调用它时?

最佳答案

您遇到的错误是关于 queries 没有方法 each - 您应该使用 forEach 代替。
除此之外,您应该从函数中返回 promise :

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 是您的匿名函数之一)时,将创建 Promise。
现在您可以根据需要处理它,例如:

let p = item(collection);
p.then(...).catch(...)

关于javascript - Node.js ES6 中的 Promise 何时启动代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44201270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com