0

How can i manage to run this :

for(let i=0; i<3; i++){
   setTimeout(function() {console.log("A")}, 500);
}

console.log('B');

and make it synchronous to get the following output :

AAAB

I oversimplified the situation here, but in my code, I have a for loop that iterates 3 times. Inside it, I first make an external API request which body's returned using a promise. I use then(). to run the suite of the loop's content. BUT after the loop, I want to refresh the page.
The issue is that the page refreshes before the loop has finished :

// API call
function call(src,dest) {
    return new Promise(function (resolve,reject) {
        request('https://api.skypicker.com/flights?flyFrom='+src+'&to='+dest+'&dateFrom='+date+'&dateTo='+nextDate+'&partner=picky', function (err, res, body) {
            if (!err && res.statusCode === 200) {
                resolve(body);
            } else {
                reject(err);
            }
        });
    })
}

Here is the for loop:

if (arr.length > 0 && arr[0]!==""){
            for (let k = 0; k < arr.length ; k++){
                    let flight = call(dataPays.pays,arr[k]);
                    flight.then(function (result) {
                        info.dest = result;
                    }).catch(function (error) {
                        console.log("ERROR :" + error );
                    }).then(function () {
                        let object = JSON.parse(info.dest);
                        let myArray = object.data;
                        dataPays.dest[count]=dataPays.pays + " --> " + arr[k]+ ": ";
                        count++;
                        //start
                        for (let j = 0; j < myArray.length ; j++){
                            if (!valueExists(checker,object.data[j]["flyTo"])){
                                let string = "dest_" + j;
                                dataPays.dest[count]="  from "+object.data[j]["flyFrom"] + "  to  " +object.data[j]["flyTo"] + "  " + object.data[j]["price"]+ "€  " ;
                                checker[string] = object.data[j]["flyTo"];
                                count++;
                            }
                        }
                    }).then(function () {
                        console.log("after then  " + k + "  -- " );
                        if (k === arr.length-1){                
                            console.log("refreshing");
                            res.redirect(req.get('referer'));                   
                        }
                    })
            }
    }

Here, We can see that I've tried to fix the issue by using the value of k to refresh the page at the last iteration of the loop. However, The console.log(k) shows that its value is kind of random. The loop is not waiting for the previous iteration to finish before running again.

I also tried to put the redirect part outside the for loop but it doesn't work either.

My guess is that I should use a callback, But I have no idea how to do it in this code.

1 Answers1

0

Put all your promises in an array and use Promise.all();

Simplified example:

let promises = [];
for (let i=0; i<3; i++) {
    promises.push(methodThatReturnsPromise());
}
return Promise.all(promises).then((results) => {
    console.log('This will reliably execute after all promises, results are:', results);
})

Note that results is an array with results of respective promises, following the order of the promises in the input array.

user2551768
  • 488
  • 6
  • 11