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.