I've been trying loop through an array of items such that each is used in an operation that returns a promise, but within that promise there's another promise. I'm not getting the desired flow. What am I doing wrong? Or is there a better way. I couldn't use much chaining because of the conditionals. I have tried async/await in several ways still the same undesired result.
The codes have been simplified for clarity. The fetch
calls are actually database operations, but the behaviours are still the same; also I've used a single-element array in this case.
var names = ['mike'];
console.log('black');
var fn = function doThings(name) {
return new Promise((resolve) => {
console.log('blue');
var char = name.substr(1);
getNum(char);
console.log('violet');
function getNum(ch) {
console.log('green');
fetch('fetchfrom.url')
.then(response => {
console.log('orange');
return response.json();
})
.then(n => {
if(n === 2) {
console.log('red1');
fetch('fetchfrom.url')
.then(response => {
console.log('yellow');
return response.json();
}).then(color => {
if(n === 2) {
console.log('red2');
resolve(5);
}
else {
console.log('brown2');
resolve(10);
}
});
console.log('lilac');
} else {
console.log('brown1');
resolve(20);
}
});
}
})
}
var actions = names.map(fn);
Promise.all([actions])
.then(() => {
console.log('done');
})
I expect the logs to be in the order (assuming n always equals 2): black...blue...green...orange...red1...yellow...red2...lilac...violet...done
But instead i consistently get: black...blue...green...violet...done...orange...red1...yellow...red2...lilac