首页 > 解决方案 > 反复等待异步发布请求

问题描述

我想反复做一个POST请求,如下:

async function request(spec){
    // POST
    fetch('/spec', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            spec: spec
        })
    })
        .then(function(response){
            if(response.ok){
                console.log('POST success.');
                return;
            }
            throw new Error('POST failed.');
        })
        .catch(function(error){
            console.log(error);
        });
}
async function repeatRequest(times){
   for(let i=0; i<times; i++)
      await request("");
}

但这不起作用,因为我不知何故没有正确使用异步编程。不知何故,即使在异步 js 上花费了数小时后,我也不知道我是否仍然得到它。

编辑:此代码在客户端。

标签: javascriptasynchronouspostasync-await

解决方案


fetch要按顺序执行请求,您需要在异步函数的顶层返回 promise(的返回值)。这样await,for循环中的关键字将等待函数的结果:

(请注意,我已将目标 URL 更改为在此处运行示例。)

async function request(pokemon) {
  return fetch('https://pokeapi.co/api/v2/pokemon/' + pokemon)
    .then((response) => {
      if (response.ok) {
        console.log('request success.');
        return;
      }
      throw new Error('request failed.');
    })
    .catch((error) => {
      console.log(error);
    });
}

async function repeatRequest(times) {
  for (let i = 0; i < times; i++) {
    console.log(i);
    await request("pikachu");
  }
}

repeatRequest(5);

或者,您可以使用完整的 async/await,如下所示:

async function request(pokemon) {
  try {
    let response = await fetch('https://pokeapi.co/api/v2/pokemon/' + pokemon);

    if (!response.ok) {
      throw new Error('request failed.');
    }
    
    console.log('request success.');
    return response;
  } catch (error) {
    console.log(error);
  }
}

async function repeatRequest(times) {
  for (let i = 0; i < times; i++) {
    console.log(i);
    await request("pikachu");
  }
}

repeatRequest(5);


推荐阅读