如何在继续之前等待异步完成 - JS

时间:2021-02-25 09:54:24

标签: 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 locally (and save in db)
4- upload it to s3
5- update bucketapiversion_file locally (using versionning)

**每个点都是一个异步函数 但是当我调用这些 api 时,您可以在终端中看到该顺序不受尊重here

这两个 api 被调用并同时运行,这使我的代码无法正常运行,我相信。每个 api 同时检查 s3 版本(即使它不应该是相同的!)并同时写入和上传它,即使首先调用网络更新然后更新 as we can see 我怎样才能防止这种情况发生?

1 个答案:

答案 0 :(得分:1)

这里的关键是每一步都是异步的。您必须等待每个步骤完成,因为您需要强制执行顺序并使用每个异步函数的输出。我会尝试勾勒出实现的草图,以便您了解这个想法。

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。