2

I have 2 separate functions, both are making a GET request. After completing, I need to add up number from response1 with number from response2. So basically I want make 3rd function, that will add up results from previous 2 functions. The problem is that 3rd function executes before 1st and 2nd.

I tried callbacks, but seems it's not working as expected. Below you can find a simple example and I want to understand the basics before implementing it in my code. Example with callback I tried:

function first(callback){
    setTimeout(function(){
        console.log(1);
    }, 500);
    callback()
}

function second(){
    console.log(2);
}

function third(){
    first(second);
}

third();

Example without callback:

function first(){
    setTimeout(function(){
        console.log(1);
    }, 500);
}

function second(){
    console.log(2);
}

function third(){
    first();
    second();
}

third();

https://jsfiddle.net/u8a592pz/

Currently this function executes as:

2
1

What I want to get:

1
2
  • `I tried callbacks` I don't see them. Pass a callback to `first` that runs after the timeout completes, and have that passed callback be `second` – CertainPerformance Apr 14 '19 at 18:59
  • It's displaying that way because of `setTimeout()` function, your result is displayed by 500ms, remove it and it should solve the problem. – Akash Jain Apr 14 '19 at 19:00
  • @CertainPerformance Could you please help me with a callback, maybe I understand it wrong? Will update my question with what I tried in a moment. @AkashJain `setTimeout()` is required to simulate a delay in executing 1st function – moonrider_unchained Apr 14 '19 at 19:01
  • You need to call the callback *after* the timeout finishes, not before. Fix that, and it should work as expected – CertainPerformance Apr 14 '19 at 19:08

1 Answers1

5

Wrap the content of first in a Promise and return it. And make third as async function and use await before first()

function first(){
    return new Promise(res => {
      setTimeout(function(){
        console.log(1);
        res();
      }, 500);
    })
}

function second(){
    console.log(2);
}

async function third(){
    await first();
    second();
}

third();
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73