0

I already know this question has been asked many times but I can't figure out how to oganize my code. I'm coming from C/C++ language and still have the way of think, and what I'm writting in JS looks 'meaningless'.

I'm using a recursive function in order to generate a travel on a map. The thing is I need to make 2 asynchronous call of 2 different APIs, the second depending on the result of the first one.

Actually, i'm always using callback functions, like this :

    function asyncFunction(param, callbackF) {
      // ... //
      $.get(url, function(data, status) {
        callbackF(data, status);
      })
    }

    function asyncFunction2(param, callbackF) {
        // ... //
        $.get(url2, function(data, status) {
          callbackF(data, status);
        })
    }

    function recursiveFunction(param1, param2, num, tab, distance) {
      //.. stuff with parameters //
      asynFunction(param1, function(result, status) {
        // .. stuff with parameters .. //

        //.. Algo stops when distance is 0 ..//
        if(!distance) {
          asyncFunction2(param, function(data, status) {
            // Final stuff //

            return; // End
          });
        }
        else recursiveFunction(param1, param2, num, tab, distance); // parameters has been updated
      });
    }

recursiveFunction(param1, param2, num, tab, distance);

It's working but ugly with a lot of imbrication, and I can't event know if this function went wrong (ex. a call to an API failed, etc).

The question is how can I introduce Promises in this context or async/await terms in JS ? How can I turn this code into a more understanding way ?

Thanks.

1 Answer 1

1

$.get already returns a Promise-like object. You just need to get rid of callbacks and return the promise.

function asyncFunction(param) {
  // ... //
  return $.get(url)
}

function asyncFunction2(param) {
    // ... //
    return $.get(url2)
}

Now you can use async/await with your functions. Something like this should work

async function recursiveFunction(param1, param2, num, tab, distance) {
  const result = await asyncFunction(param1);
  // .. stuff with parameters .. //

  if(distance) {
    await recursiveFunction(param1, param2, num, tab, distance); // parameters has been updated
  } else {
    await asyncFunction2(param)
  }
}


recursiveFunction(param1, param2, num, tab, distance);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's works like a charm and I get to know deeper about promises and asyn/await.

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.