7

I am trying to make an async request within foreach to fetch data in order user it later but its not working for me.

I know Array.Foreach is a synchronous function so I even tried $.when.done but still it does not wait until it finish.

I could have used callback if it was a single value but its an array . Is there a better way to handle this by callback to achieve waiting on async request before moving next?

browseItems.forEach((browseItem: any) => {

   AsynchFunction();

   cosole.log("Step 2")  
}
function AsynchFunction(){
   console.log("Step 1")
}

I am trying to get an output like

Step 1

Step 2

3 Answers 3

9

Building on @basarat's answer, I found that this works quite well if you are using the async/await feature in TypeScript (as of TS 1.7 requiring ES6 target):

async function processData(data: any[]) {
  const promises = data.map(async (item) => {
    await doSomeAsyncStuff(item);
    //you can do other stuff with the `item` here
  });
  await Promise.all(promises);

  //you can continue with other code here that will execute after all the async code completes
}

async function doSomeAsyncStuff(value) {
  return new Promise((resolve, reject) => {
    //call some async library or do a setTimeout and resolve/reject the promise
  });
}

Update: async and await are now available for TypeScript code targeting ES5 as well in the master branch of TypeScript, soon to be released as TypeScript 2.1. You can install it today using npm install --save-dev typescript@next

Update: This feature is available for all ES targets in the current version of TypeScript. The one caveat I have noticed is that if you are targeting ES5 or ES3, you will need to provide a Promise polyfill or the code will fail on older browsers.

2
  • this looks neat, but doesn't seem to actually work. First, you'd need to return something from the map... but even then it doesn't appear to wait afterward.
    – dcsan
    Aug 7, 2016 at 5:19
  • @dcsan, in TypeScript, when you await a function that returns a promise, the containing async function automatically returns a Promise, even if the promise is Promise<void>. You don't need to return anything out of the .map function. I have used this pattern many times and it works well.
    – Joe Skeen
    Aug 9, 2016 at 19:55
6

Is there a better way to handle this by callback to achieve waiting on async req before moving next

If you are using promises you can use a function like Promise.all:

var promises = browseItems.map((browseItem: any) => AsynchFunction());
Promise.all(promises).then((values)=>{});
2

Once you start using async functions, you go either of two ways: callbacks or promises. In the case of the above code, you just need to define a callback function to be called after the async function returns. See sample below:

browseItems.forEach((browseItem: any) => {
   AsynchFunction(postProcess);   
}
function AsynchFunction(callback){
   console.log("Step 1");
   if(asyncProcessDone){
       callback();
   }
}
function postProcess(){
    console.log("Step 2")
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.