0

I have three api request to work asynchronous, but the second request is working before the first request is completed. How do I get the second api request to start after completing the first request and then third after the second?

async doSave(event)
{
  await this.server.post('/insertRecord',{name:'joe'});

            //have to work after completion of above request

  await this.server.post('/changeCountry',{countryName:'US'});

          //have to work after completion of above request

  await this.server.post('/satge',{stage:'fifth'});
}
4
  • Well, just like you wrote it. Does it work? Commented Nov 22, 2018 at 8:54
  • No its not working Commented Nov 22, 2018 at 8:56
  • if your app breaks because of the order of requests, your doing it wrong. Commented Nov 22, 2018 at 8:56
  • What kind of API / Object is this.server? Commented Nov 22, 2018 at 8:57

3 Answers 3

3

If your second request starts before your first request, it means that the Promise returned by this.server.post resolves before the request is complete. Alternatively, it does not return a Promise at all in which case it starts your asynchronous request, and then runs the next line in this function after this.server.post returns.

Sign up to request clarification or add additional context in comments.

Comments

1

The server should return a promise, in that case await will wait for it to resolve. In the code below I did a mock of the server to test the whole code. It will do the work synchonously.

const server = {
  post: function(url, data) {
    const time = 300 + Math.random() * 1500;
    console.log("Posting at " + url + " ... (" + Math.round(time) + "ms)");
    return new Promise(resolve => setTimeout(() => resolve(), time)
    );
  }
};

async function doSave(event) {
  await server.post('/insertRecord', {
    name: 'joe'
  });

  //have to work after completion of above request
  console.log('doing Work after InsertRecord');
  await server.post('/changeCountry', {
    countryName: 'US'
  });

  //have to work after completion of above request
  console.log('doing Work after changeCountry');
  await server.post('/satge', {
    stage: 'fifth'
  });
}
doSave();

Output:

Posting at /insertRecord ... (1306ms)
doing Work after InsertRecord
Posting at /changeCountry ... (1752ms)
doing Work after changeCountry
Posting at /satge ... (1616ms)

Check this link for more information about await, async, promises

Comments

0

ideally this.server - should return promises (axios for eg returns promises), but if it does not than you can use Promises instead of Async/await and chain your requests one after another.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.