[英]In Javascript does async await wait for all nested functions to complete?
[英]Javascript Async Await wait for two functions to complete
我正在努力解决异步/等待问题。
我有以下代码调用:
submitHandler()
将表单的输入发布到 Google 表格 const scriptURL =
'GOOGLE SCRIPT URL'
const form = document.forms.emailform
fetch(scriptURL, { method: 'POST', body: new FormData(form) })
.then(response => {
console.log('Success!', response)
setFormSuccess(1)
})
.catch(error => {
console.error('Error!', error.message)
setFormSuccess(2)
})
}
childRef.current.upload()
将文件发布到 S3 ...但是我需要等待这两个函数的结果,然后才能调用另一个函数来打开一个模态并传入这两个函数的结果。
有人可以帮我吗?
非常感谢
async function onSubmit() {
setTimeout(() => {
submitHandler()
childRef.current.upload()
}, 1000)
}
//I want to wait for onSubmit to complete and then call another function which sets state and then launches a modal
编辑:我不得不在最初的问题中提到我已经尝试在我调用的所有函数中等待,但它们都不起作用
我认为您只是缺少一些“等待”声明。 我也修改了超时。
async function onSubmit() {
let sleep = function (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
await sleep(1000)
await submitHandler()
await childRef.current.upload()
}
//I want to wait for onSubmit to complete and then call another function which sets state and then launches a modal
同样在 submitHandler() 中,您没有正确使用 async-await。 您正在使用 .then 方法,该方法无法轻松与 await 结合使用。
async submitHandler() {
const scriptURL = 'GOOGLE SCRIPT URL'
const form = document.forms.emailform
try {
let response = await fetch(scriptURL, { method: 'POST', body: new FormData(form) })
console.log('Success!', response)
setFormSuccess(1)
} catch(error) {
console.error('Error!', error.message)
setFormSuccess(2)
}
}
如果您仍想捕获错误,则必须将提取包装在 try 块中。
你可以使用Promise.all()来等待多个 Promises,就像这样
const result = await Promise.all([submitHandler(), childRef.current.upload()]);
你的函数应该返回Promise
。 所以返回你的fetch()
submitHeader(){
const scriptURL =
'GOOGLE SCRIPT URL'
const form = document.forms.emailform
return fetch(scriptURL, { method: 'POST', body: new FormData(form) })
.then(response => {
console.log('Success!', response)
setFormSuccess(1)
return response;
})
.catch(error => {
console.error('Error!', error.message)
setFormSuccess(2)
})
}
所以在你的主要功能中,你可以
async function onSubmit() {
setTimeout(() => {
const response = await submitHandler()
// Your response will be available here
console.log(response);
childRef.current.upload()
}, 1000)
}
第一件事是,如果您想在其中await
,则需要将setTimeout
的回调标记为async
。
但是setTimeout
使用回调,因此偏离了您想要的控制流。 因此,我将使用一个简单的承诺包装器来实现它:
const promiseSetTimeout = (cb, delay) => new Promise((resolve, reject) => {
setTimeout(async () => {
const ret = await cb();
resolve(ret);
}, delay);
});
因此,您可以等待它并获得所需的控制流。
function onSubmit() {
return promiseSetTimeout(async () => {
await submitHandler();
await childRef.current.upload();
}, 1000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.