I'm working on nodejs app currently, one part of which, tests some api calls and then returns as a promise, then perform another function.
So - I'm looping through an array of promises with the following two functions:
Over all function for all apis
function testAllApis(apiList, counter = 0){
return new Promise(function(fulfill, reject){
console.log(counter);
if(counter == apiList.length){
console.log('test1');
fulfill();
console.log('test2');
}
else {
testSingleApi(apiList[counter]).then(() => {
testAllApis(apiList, counter + 1);
}).catch((e) => {
console.log(e);
reject(e);
testAllApis(apiList, counter + 1);
})
}
})
}
Function for each individual array
function testSingleApi(thisApi){
return new Promise(function(fulfill, reject){
var apiUrl = '/api/' + thisApi.substr(7).slice(0, -3) + '/testapi/';
var options = {
hostname: serverHost,
port: serverPort,
path: apiUrl,
method: 'GET',
};
var req = http.request(options, (res) => {
console.log(res.statusCode);
fulfill(res.statusCode);
});
req.on('error', (e) => {
reject(e.message);
});
req.end();
});
}
When I call this in the terminal it functions as intended, and console logs the success codes (200) of the api calls I am making, but after the third one, when 'counter' is equal to the length of the array, it goes into the if condition in the testAllApis function, console logs 'test1', then 'test2' and doesn't fulfill() at all.
Does anyone have any insight into this? I am still quite new to promises and tried searching for a solution to this online but it was quite a specific question so thought to post here instead.