I'm having trouble trying to call a chain of asynchronous functions inside an array. When I call the function individually it works without any problem like in the example below:
function consoleAll(string) {
return new Promise(function (resolve) {
console1(string).then(function () {
console2(string).then(function () {
resolve();
});
});
});
}
function console1(value) {
return new Promise((resolve) => {
console.log(value + "1");
resolve()
});
}
function console2(value) {
return new Promise((resolve) => {
console.log(value + "2");
resolve()
});
}
consoleAll('value-')
In this case the result was the below that is correct:
value-1
value-2
But when it is passed inside a loop it does not make the thread correctly and calls the functions completely out of order
function consoleAll(string) {
return new Promise(function (resolve) {
console1(string).then(function () {
console2(string).then(function () {
resolve();
});
});
});
}
function console1(value) {
return new Promise((resolve) => {
console.log(value + "1");
resolve()
});
}
function console2(value) {
return new Promise((resolve) => {
console.log(value + "2");
resolve()
});
}
//Call
['h1-', 'h2-', 'h3-'].forEach(function (string) {
consoleAll(string)
});
This time instead of writing the result below:
h1-1
h1-2
h2-1
h2-2
h3-1
h3-2
it outputing this :
h1-1
h2-1
h3-1
h1-2
h2-2
h3-3
It looks like it calls the console1 function for the entire array to then call console2.
Does anyone know the correct way to make this call? PS. I do not care if it is necessary to install some plugins to fix this.