简体   繁体   中英

How to make an API call inside for loop, withour using async await

Having a for loop inside a promise. How can i get response from getData API without using async await. The parameters used inside getData are coming from for loop.

var res = EService.webApi.get.GetActiveData(formModel.project.EID);
        res.then(
           async function (result) {
                //success
                var data = result.data;
                var eList= data.BodyData;
                var jList= [];
                for (var i = 0; i < eList.length; i++) {
                        let entity = await getData(eList[i].EntityID);
                        if (eList[i].typeID !== 16) {
                            jList.push({
                                Name: eList[i].Name + " - " + e[i].typeName + " - " + entity.Name,
                                EID: eList[i].EntityID,
                                model: eList[i],
                            });
                        } 
                    }
}

 

If I understand what you're asking, it sounds like you want to invoke all of the async requests right away but have each one await its result, rather than invoking them in serial where each one awaits the previous operation. Maybe something like this:

for (var i = 0; i < eList.length; i++) {
  (async (j) => {
    // The rest of your logic, but using the passed `j` instead of `i`
  })(i);
}

The anonymous async function isn't awaited, but internally each call to that function can await the call to getData to use its result.

Though if you want to do something with jList or any other result/side-effect afterward then you'd need to await the whole thing. Maybe put all of the promises into an array and await the array. Perhaps something like:

let promises = [];
for (var i = 0; i < eList.length; i++) {
  promises.push((async (j) => {
    // The rest of your logic, but using the passed `j` instead of `i`
  })(i));
}
Promise.all(promises).then(() => ...);

The overall goal being that all of the operations run in parallel, rather than in serial like in the original loop.

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