[英]AsyncAwait is not waiting for the fetch response
I am having a problem in executing API calls using aysnc and await. 我在使用aysnc和await执行API调用时遇到问题。 I am using fetch method to call a Spring Boot service which returns a JSON string after uploading a file. 我正在使用fetch方法来调用Spring Boot服务,该服务在上传文件后返回JSON字符串。 Before getting the status of upload file data next code is executing. 在获取上传文件数据的状态之前,正在执行下一个代码。 Help me to resolve the issue. 帮我解决问题。 Below is the code I have written - 以下是我编写的代码-
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 };
});
}
Please help to achieve functionality to wait until the completion of the upload process. 请帮助实现功能,直到上载过程完成。 Thanks in advance. 提前致谢。
requestAwait
is awaiting fetch
, but the caller function isn't awaiting requestAwait
. requestAwait
正在等待fetch
,但调用方函数未在等待requestAwait
。
Also, with several parallel API calls, I think you'll be better off with Promise.all()
instead of the async-await
recipe. 另外,通过几个并行的API调用,我认为使用Promise.all()
代替async-await
配方会更好。
The code is not waiting, because const requestAwait
is a promise. 该代码没有等待,因为const requestAwait
是一个承诺。 So when you cast requestAwait()
the code continues to file.upload = true
, without waiting for the fuction to end. 因此,当您投射requestAwait()
,代码将继续file.upload = true
,而无需等待功能结束。
As it is right now, to make it work You must add ASYNC inside the map here : 现在,要使其正常工作,必须在此处的地图内添加ASYNC:
acceptedFiles.map( async (file) => { ...function } )
Then before the cast of the requestAwait
. 然后在requestAwait
。
await requestAwait();
file.uploaded = true;
return file;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.