haly
haly

Reputation: 15

How to wait for the async to complete before continue - JS

Objective: Update and add products in a form and call two apis simultaneously.

each api is following those steps :

 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)

**each point is an async function but when I call those apis the order is not respected as you can see in the terminalhere

those two apis are called and running in the same time which make my code not running properly I believe. Each api check at the same time the s3 version (both same even if it shouldn't be!) and write and upload it simultaneously even if in network update is called first then update as we can see How can I prevent that?

Upvotes: 0

Views: 144

Answers (1)

rm_
rm_

Reputation: 777

The key here is that every step is asynchronous. You have to wait for each step to complete since you need to enforce order and also use the output of each asyncrhonous function. I'll try to sketch the implementation so you'll get the idea.

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) {
    [...]
}

The above code is ES8+ compliant, if you can't use ES8+ i recommend using Promises.

Upvotes: 1

Related Questions