/ / Петля з обіцянками [дублювати] - javascript, node.js

Цикл з обіцянками [дублікат] - javascript, node.js

З урахуванням наведеного нижче коду:

var arr = ["one", "two"]

for (index in arr) {
console.log("outside promise:", arr[index])

myPromise().then(function(response) {
console.log("inside promise:", arr[index])
})
}

Мій вихід:

// outside promise: one
// outside promise: two
// inside promise: one
// inside promise: one

Чому хак консолі вихід всередині обіцянки не "T циклу корито значення?

Відповіді:

0 для відповіді № 1

Як @Jaromanda X зазначено в коментарі, правильний вихід буде:

// outside promise: one
// outside promise: two
// inside promise: TWO
// inside promise: TWO

Оскільки обіцянки будуть вирішені, коли індекс вже буде 1, не 0. Якщо ви отримуєте різні результати в консолі, це може бути stdout проблеми паралелізму. Спробуйте додати результати до масиву, а потім вивести його;

const arr = ["one", "two"];
let results = [];

for (index in arr) {
results.push(`outside promise: ${arr[index]}`)

myPromise().then(function(response) {
results.push(`inside promise: ${arr[index]}`)
})
}

console.dir(results);