Search code examples
javascriptasync-awaites6-promise

Javascript - Handling asynchronous race condition


N.B. BEFORE DELETING AS DUPLICATE: I realise that similar questions have been asked many times before, however I have spend several hours trying to implement this using other people's responses, most recently the response from noseratio in this thread Proper way to wait for one function to finish before continuing? and have had no success.


I have a nodeJS server which successfully returns data when my function f1 requests it, and another function f2 which calls f1 and then is meant to do something with the output of this async function. I am trying to do this with async/await syntax and an additional promise in f2, as shown below.

async function f1(){
   try{
       let response = await fetch('MY SERVER URL');
       let data = await response.json();
       return await data;
   }
   catch(e) {
       alert(e);
   }
};


function f2() {
    var promise = f1();
    promise.then(function(result) {
        JSONdata = promise.markers;
        console.log("JSON read into f2");
    })    

    console.log(JSONdata);

and then f2 goes on to do other stuff...

However the issue is that I am experiencing race conditions with the result of f1 not being returned in time to be able to do anything with it, and so the variables are undefined.

Any help on how to mitigate this would be appreciated, thanks.


Solution

  • You should either move the logic that makes use of the f1 result inside the then callback.

    function f2() {
        var promise = f1();
        promise.then(function(result) {
            var JSONdata = result.markers;
            console.log("JSON read into f2");
    
            console.log(JSONdata);
        });
    }
    

    Or change f2 to an async function so you can await the return value.

    async function f2() {
        var result = await f1();
        var JSONdata = result.markers;
        console.log("JSON read into f2");
    
        console.log(JSONdata);
    }
    

    If you haven't already, check out the MDN Using Promises guide, which explains them pretty thorough. When you have an understanding of how promises work async/await will also become a lot more easy to understand.