简体   繁体   中英

Continue .map loop after util.promisify request fails in iteration (async await)

I have the below async function taking in an array of 4 objects. The first one is processed in a.map loop that executes a query and results in an error (in the await executeQuery(queryString)). When this first object is completed processing, the loop ends and the other 3 objects are not processed.

async function myFunction(arrayOfObjects, param1) { 

     const promises = arrayOfObjects.map(async function (currElement, i) {
          var queryString = 'www.querystring.com?APIparameter=param1';
          
          const executeQuery = util.promisify(request);

          await executeQuery(queryString).then(data => {

          //process data here using currElement, i
          
          }).catch(err => console.log('error: ', err));   
     });

     await Promise.all(promises).catch();
}

I originally only had await Promise.all(promises) and thought revising it to await Promise.all(promises).catch(); would do the trick but it is still failing out on the first object iterated.

I was wondering how best to achieve continuing the.map loop after an error hits the catch in the executeQuery.

Please and thank you!

Not 100% sure what's happening with this code but there are a few things I would change. Firstly it's not good practice to use an await inside a loop and secondly, your promises array is probably not what you expect as the await is yielding until each promise is resolved inside the loop. Return the Promise from the map function to generate an array of Promises that will each resolve and process the data in their own time. You can then await all the promises and catch any errors using try/catch . Something similar to the following should do what you are expecting...

async function myFunction(arrayOfObjects, param1) {

    const executeQuery = util.promisify(request); 

    const promises = arrayOfObjects.map((currElement, i) => {

        const queryString = 'www.querystring.com?APIparameter=param1';

        return executeQuery(queryString).then(data => {

             // process data here using currElement, i
        });   
    });

    try {

        await Promise.all(promises);

        // all promises will be resolved here

    } catch (err) {
        console.log('error: ', err);
    }
}

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