重复等待异步post请求



我想重复做一个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("");
}

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

编辑:此代码位于客户端。

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

(注意,我已经更改了目标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);

最新更新