Skip to content Skip to sidebar Skip to footer

Resolve Promises In Iteration

I'm looking to iterate over a number of promises but the lambda function is completing before they are resolved. module.exports.handler= async(event, context, callback) => { l

Solution 1:

This is because awaits in loops that require a callback will not be processed synchronously (See this).

One way you could avoid this is you could build an array of promises, and use Promise.all to await completion.

Example:

module.exports.handler = (event, context, callback) => {
    let a = {'a': 'b', 'x': 'foo', 'y': 'bar'};
    let b = {'i': 'n'};

    let promises = []
    Object.keys(a).forEach(ax => {
        Object.keys(b).forEach(bx => {
            promises.push(validate(ax, bx));
        })
    })

    Promise.all(promises)
        .then(results => {
            //do stuff with results
        })
        .catch(error => {
            //handle error
        })
}

Solution 2:

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise.

you can use @Michael solution just replace Promise.all with Promise.allSettled

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise mozilla Doc.

The Promise.all() method returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled or when the iterable contains no promises. It rejects with the reason of the first promise that rejects mozilla doc.

module.exports.handler = (event, context, callback) => {
    let a = {'a': 'b', 'x': 'foo', 'y': 'bar'};
    let b = {'i': 'n'};

    let promises = []
    Object.keys(a).forEach(ax => {
        Object.keys(b).forEach(bx => {
            promises.push(validate(ax, bx));
        })
    })

    Promise.allSettled(promises)
        .then(results => {
            //do stuff with results
        })
        .catch(error => {
            //handle error
        })
}

const promise1 = Promise.resolve(3);
const promise2 = newPromise((resolve, reject) =>setTimeout(reject, 100, 'foo'));
const promise3 = Promise.resolve(4);
const promises = [promise1, promise2,promise3];

Promise.allSettled(promises).
  then((results) => results.forEach((result) =>console.log(result.status)));

// expected output:// "fulfilled"// "rejected"// "fulfilled"

Post a Comment for "Resolve Promises In Iteration"