javascript - 反复等待异步发布请求
问题描述
我想反复做一个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 上花费了数小时后,我也不知道我是否仍然得到它。
编辑:此代码在客户端。
解决方案
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);
推荐阅读
- javascript - mxGraph:来自外部按钮的单击事件
- java - Class.getDeclaredMethods 为没有参数和 void 返回类型的类方法抛出 NoClassDefFoundError
- flutter - 修复 Flutter 的 Visual Studio 代码中的双引号/单引号警告
- go - 当错误已经返回时,从延迟函数返回错误
- sql - SQL连接两个表并创建新列
- json - 如何使用 ajax 调用将 json 数据填充到图表中?
- google-api - 如何在 Gmail API 中下载 credentials.json 启用 Java
- python - 使用 Panda 绘制时间序列
- spring-boot - 启用 CORS 原始 graphql
- sql - 在 Exec 存储过程命令 SQL Server 中使用表列