简体   繁体   中英

When start code in Promise in Node.js ES6?

I make a method that create a promise for each element in array.

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?

Well the error you have is about queries has not method each - you should use forEach instead.
Bescides you should return promise from your function:

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.
And now you can handle with it whatever you need, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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