J.Done
J.Done

Reputation: 3043

nodejs promises in loop

let token = null;
let allData = [];
while( true) {
  getData( token).then( function( data, nextToken){
    token = nextToken;
    allData.push( data);
  });
  if( token == null) break;
}
return allData;

As you know this code is not work as I excepted because while loop will continue before token value is set as nextToken value. Is there any way to get all data?

Upvotes: 2

Views: 171

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32127

You could use a recursive function for this.

function getDataRecursive(token, data = []) {
    return getData(token).then((newData, nextToken) => {
        if(nextToken === null) {
            return [...data, newData];
        }
        return getDataRecursive(nextToken, data);
    });
}

getDataRecursive(token).then((data) => {
    console.log(data); // Will contain your array of data
});

Upvotes: 2

Related Questions