2017-05-25 72 views
0

考慮下面的代碼:環路與承諾

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 

爲什麼砍的承諾內的控制檯輸出不循環谷值?

+1

你能不能更清楚一點,我真的不明白你說的是什麼問題? –

+0

定義了myPromise?預期的結果是什麼?你的循環裏面的 – guest271314

+0

試試var x = arr [index];然後console.log(x)在promise裏面 – PenAndPapers

回答

0

由於@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); 
+0

記錄數值或將其推送到數組沒有區別(根據定時)。問題是一樣的。 – Thomas

+0

@Thomas哪個問題? –

+0

,閉環內的'array [index]'將在循環完成迭代之後被解析。對於所有具有相同索引的迭代,最後一個。 – Thomas