简体   繁体   中英

Promise pattern - using Promise.all()

I have a chain of functions for grabbing some JSON data, then inserting the data into a database. I want to wait for all of the inserts to complete, so I am trying to use Promise.all() . I know that Promise.all() needs an array (or iterable) of promises.

Here is my chain:

fetchBody().then(parseBody).then(prepareInserts).then(insertAll).then(function() {
    console.log('done')
}); // Error handling and more stuff here

My code is hanging on the prepareInserts function:

// Returns an array of promises, which will be iterated over in Promise.all();
const prepareInserts = function (data) {
    return new Promise(function (resolve, reject) {
        const promises = data.map(function (d) {
            return new Promise(function (resolve, reject) {
                connection.query(queryString, [d.a, d.b, d.c, d.d], function (error) {
                    if (error) {
                        reject(error);
                        return;
                    }
                    resolve();
                });
            });
        });
        resolve(promises);
    });
};

I think I have a fundamental misunderstanding of how I should be laying out the prepareInserts function; the queries are being executed there, which is not what I want. I want them to be inserted in the last function in the chain:

const insertAll = function (promises) {
    return Promise.all(promises);
};

I think this is what you want:

const doInserts = data => {
  return Promise.all(data.map(d => 
     new Promise((resolve, reject) => {
       connection.query(queryString, [d.a, d.b, d.c, d.d], error => {
         if (error) {
           reject(error);
           return;
         }
         resolve(/* to what?? */);
       });
     }));
  });
};

fetchBody().then(parseBody).then(doInserts).then(function() {
  console.log('done')
});

You return a Promise.all() promise that resolves when all internal promises are resolved (with no value?). Each internal promise is created by mapping a data item (from data ) to a promise, which is resolved or rejected depending on the query result.

If you could promisify connection.query outside of this code, it would make for a cleaner result, where you map to " promisifiedQuery " directly.

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