0
votes

Considering the following code in ui5/javascript. Inside for loop the code should be executed always in the sequence: getData1, getData2, fnc1(i), getData3, getData4, fnc2(i) for each "i" before calling function fnc3(). As of now fnc3 is called before i is incremented:

for (var i = 0; i <= intNum; i++) {

    getData1(url1, true).then(function() {
        getData2(url2, true).then(function() {
            fnc1(i);
            getData3(url3, true).then(function() {
                getData4(url4, true).then(function() {
                    fnc2(i);
                })
            })
        })
    })
}
fnc3();

All four getData functions do some operations and then return a promise.

function getData() {
    var oModel = new JSONModel();
    return oModel.loadData(url, true); //asynchronous loading data and returns a promise
}

Any solution how can I make it work? Any help appreciated. Thanks

1
Put the for() loop inside a Promise and call func3() inside the then of that promise. - Randy Casburn
Use async/await? It would be much cleaner and more intuitive. blogs.sap.com/2019/01/17/… - Rohim Chou

1 Answers

0
votes

you are turning promises in a callback hell, return each promise and chain it with then properly. use let instead of var also at for loop, var is not block scoped. you could add an if statement at last then block to run fn3:

for (let i = 0; i <= intNum; i++) {
  getData1(url1, true)
    .then(() => getData2(url2, true))
    .then(() => {
      fnc1(i)
      return getData3(url3, true)
    })
    .then(() => getData4(url4, true))
    .then(() => {
      fnc2(i)
      if(i === intNum) fnc3()
    })      
}