我在使用 aysnc 和 wait 执行 API 调用时遇到问题。我正在使用 fetch 方法调用 Spring Boot 服务,该服务在上传文件后返回 JSON 字符串。在获取上传文件数据的状态之前,正在执行下一个代码。帮助我解决问题。下面是我写的代码 -
endProgressSimulation(uploadingFiles) {
this.setState(({ acceptedFiles }) => {
const updatedFiles = acceptedFiles.map(file => {
if (uploadingFiles.map(loadingFile => loadingFile.name).includes(file.name)) {
const formData = new FormData();
formData.append('file', file);
const requestAwait = async() => {
console.log("Sending fetch");
const response = await fetch('http://localhost:5002/Upload/',{
method: 'post',
body:formData
})
console.log("Got response...");
const json = await response.json();
console.log("async/await based");
console.log(json);
}
requestAwait();
file.uploaded = true;
return file;
} else {
file.uploaded = false;
return file;
}
});
return { acceptedFiles: updatedFiles };
});
}
请帮助实现等待上传过程完成的功能。提前致谢。
最佳答案
requestAwait
正在等待 fetch
,但调用方函数未在等待 requestAwait
。
此外,对于多个并行 API 调用,我认为使用 Promise.all()
而不是 async-await
配方会更好。
关于javascript - AsyncAwait 不等待获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57922556/