繁体   English   中英

什么时候在Node.js ES6中的Promise中启动代码?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM