Search code examples
javascriptnode.jsecmascript-6promisees6-promise

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?


Solution

  • 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(...)