Javascript 如何在继续之前等待异步完成-JS
目标:在表单中更新和添加产品,并同时调用两个API 每个api都遵循以下步骤:Javascript 如何在继续之前等待异步完成-JS,javascript,asynchronous,promise,aws-sdk,Javascript,Asynchronous,Promise,Aws Sdk,目标:在表单中更新和添加产品,并同时调用两个API 每个api都遵循以下步骤: 1- check the local bucketapiversion_file, if it is as the s3 one don't download the file if it is different download file locally and update bucketapiversion_file then 2- add or edit the file 3- save the file
1- check the local bucketapiversion_file, if it is as the s3 one don't download the file if it is different download file locally and update bucketapiversion_file
then 2- add or edit the file
3- save the file locally (and save in db)
4- upload it to s3
5- update bucketapiversion_file locally (using versionning)
**每个点都是一个异步函数
但是,当我调用这些API时,顺序并不像您在终端中看到的那样受到尊重
这两个API被同时调用和运行,这使我的代码不能正常运行。每个api同时检查s3版本(即使它不应该是相同的!),并同时写入和上载它,即使先调用in-network update,然后再调用update
如何防止这种情况发生?这里的关键是每个步骤都是异步的。您必须等待每个步骤完成,因为您需要强制执行顺序并使用每个异步函数的输出。我将尝试勾勒出实现的草图,这样你就会明白了
async function doProcess() {
let processInput = {}
let stepOneOutput = await stepOne(processInput)
let shouldEdit = decideBasedOnOutput(stepOneOutput)
if(shouldEdit) {
let stepTwoOutput = await stepTwo(stepOneOutput)
}
[...]
}
async function stepOne(stepOneInput) {
[...]
}
async function stepTwo(stepTwoInput) {
[...]
}
上面的代码符合ES8+标准,如果您不能使用ES8+,我建议您使用Promissions。谢谢@rm_u。这就是我正在做的,但是如果同时调用api会怎么样。。如果您是基于console.log消息的顺序,那么如何防止这种情况发生,您不应该这样做。控制台不保证是同步的。更安全的做法是根据网络选项卡时间线或调试器断点来估计执行顺序,以验证正确的流。如果流看起来很奇怪,那么您很可能会跳过等待异步调用,或者发生错误,从而扰乱流。