skrite
skrite

Reputation: 327

how to assemble results of async requests in javascript

ok, so need to build an array of messages. I have a database table that has message information that relies on another table. I can pull the results with a promise, but when i iterate over the rows in the result, i cannot keep it together.

let messages = [];

dbOps.getAll(dbCon, "expo_outbox")
 .then(function(rows){

// iterate for each message
for (var i = 0; i < rows.length; i++){
    mobileMessage = rows[i];

    dbOps.getById(dbCon, mobileMessage.mobile_device_id, "mobile_devices")
        .then(function(mobileDevice) {
            regKey = mobileDevice.reg_key;
            console.log(` reg key ${regKey} gets ${mobileMessage.message}`);
            messages.push({
              to: regKey,
              sound: 'default',
              body: mobileMessage.message
           })
    })
}

how do I assemble this messages array and make myself able to operate on it knowing it has finished its background requests ? thanks...

Upvotes: 0

Views: 40

Answers (1)

Juanlu
Juanlu

Reputation: 77

You can use Promise.all:

const promises = [
    new Promise(resolve => setTimeout(resolve, 0, 1)),
    new Promise(resolve => setTimeout(resolve, 0, 2))
];
Promise.all(promises)
    .then(data => {
        console.log("All promises resolved!", data);
    })
    .catch(err => {
        console.log("Error executing promise");
    });

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Upvotes: 1

Related Questions