如何在继续之前等待异步完成 - JS
How to wait for the async to complete before continue - JS
Objective:在一个表单中更新和添加产品,同时调用两个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 locally (and save in db)
4- upload it to s3
5- update bucketapiversion_file locally (using versionning)
**每个点都是一个异步函数
但是当我调用那些 apis 时,正如您在终端here
中看到的那样,订单没有得到遵守
同时调用了 api 和 运行,这使我的代码不正确 运行 我相信。每个 api 同时检查 s3 版本(即使它不应该是相同的!)并同时写入和上传它,即使在网络中先调用更新然后更新 as we can see
我怎样才能避免这种情况?
这里的关键是每一步都是异步的。您必须等待每个步骤完成,因为您需要执行命令并使用每个异步函数的输出。我会尝试勾勒出实现的草图,这样你就会明白了。
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+我推荐使用Promises。
Objective:在一个表单中更新和添加产品,同时调用两个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 locally (and save in db)
4- upload it to s3
5- update bucketapiversion_file locally (using versionning)
**每个点都是一个异步函数 但是当我调用那些 apis 时,正如您在终端here
中看到的那样,订单没有得到遵守同时调用了 api 和 运行,这使我的代码不正确 运行 我相信。每个 api 同时检查 s3 版本(即使它不应该是相同的!)并同时写入和上传它,即使在网络中先调用更新然后更新 as we can see 我怎样才能避免这种情况?
这里的关键是每一步都是异步的。您必须等待每个步骤完成,因为您需要执行命令并使用每个异步函数的输出。我会尝试勾勒出实现的草图,这样你就会明白了。
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+我推荐使用Promises。