如何调用异步函数作为响应

how to call async function in response

我需要在响应函数中使用 await,但我不知道如何使用。
(注意:func2()是一个异步函数)

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
      }  
    }) 
  }
}

我必须等待 func2,我该怎么做?

我试过这个:

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();   
        }  
      }) 
  }
}

如果不混合使用 await.then(),通常会更容易。由于您想对两个操作进行排序,而且您似乎也希望对 for 循环进行排序,因此仅使用 await.

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

您可以去掉 .then() 并改用 await

await func1 并获取 value 然后检查 value 是否满足条件,如果满足 await func2 .

查看下面的演示片段:

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();