how to call async function in response

Viewed 191

I need to use await in a response function, but I couldn't figure out how.
(Note: func2() is an async function)

async function get_data() { 
  for (i = 0; i < 10; i++) {
    // http request, returns json...
    await func1(data1, data2).then(json => {   
      if (json.value < 100) {
        await func2(); //error => await is only valid in async function
      }  
    }) 
  }
}

I have to wait for func2, how can I do that?

I tried this:

async function get_data() { 
  for (i = 0; i < 10; i++) {
    await func1(data1, data2).then(json =>
      async function() { // nothing happens, function doesnt work.
        if (json.value < 100) {
          await func2();   
        }  
      }) 
  }
}
2 Answers

It's generally easier if you don't mix await and .then(). Since you want to sequence two operations and it appears you want the for loop to be sequenced too, it's simpler with just await.

async function get_data() {
  for (let i = 0; i < 10; i++) {
    let json = await func1(data1, data2);
    if (json.value < 100) {
      await func2();
    }
  }
}

You can get rid of .then() and use await instead.

await func1 and get the value and then check if the value satisfies the condition and if it does await func2.

Check the demo snippet below:

async function get_data() {
  for (i = 0; i < 10; i++) {
    const { value } = await func1("Hello", "World");
    if (value < 100) {
      console.log(await func2(value));
    }
  }
  console.log("END!")
}

const func1 = (d1, d2) =>
  new Promise((res) => setTimeout(() => res({ value: Math.random(0) * 200 }), 200));

const func2 = (v) => new Promise((res) => setTimeout(() => res(v), 200));

get_data();

Related