2 回答

TA貢獻1906條經驗 獲得超3個贊
.then接受一個函數作為參數,但你正在做:
p.then(fun(v))
這會fun 立即調用,無需等待p解決,并將返回的 Promise 傳遞給.then。就像做
Promise.then(Promise.resolve(6))
// ^^^ but .then only accepts a function as a parameter
這沒有意義。
更改為回調,在調用時調用fun并返回fun的 Promise:
var arr = [30, 40, 10, 50, 20];
var fun = function(n) {
console.log("Before Promise => n: " + n);
return new Promise(resolve => {
console.log("After Promise => n: " + n);
setTimeout(() => {
console.log("Promise Resolved => n: " + n);
resolve(0);
}, n*30);
});
}
arr.reduce((p, v) => p.then(() => fun(v)), Promise.resolve(0));
// ^^^^^^

TA貢獻1805條經驗 獲得超9個贊
Array.reduce()將減少上述內容,如下 Promise 鏈
是的。
為什么輸出不符合預期?
因為承諾“鏈條”斷了。為了正確鏈接,您需要將回調函數傳遞給then:
Promise.resolve(0).then(() => fun(30)).then(() => fun(40)).then(() => fun(10)).then(() => fun(50)).then(() => fun(20));
// ^^^^^ ^^^^^ ^^^^^ ^^^^^ ^^^^^
在你的減速器中做同樣的事情:
arr.reduce((p, v) => p.then(() => fun(v)), Promise.resolve(0));
添加回答
舉報