2 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
.then接受一個(gè)函數(shù)作為參數(shù),但你正在做:
p.then(fun(v))
這會(huì)fun 立即調(diào)用,無(wú)需等待p解決,并將返回的 Promise 傳遞給.then。就像做
Promise.then(Promise.resolve(6))
// ^^^ but .then only accepts a function as a parameter
這沒有意義。
更改為回調(diào),在調(diào)用時(shí)調(diào)用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貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
Array.reduce()將減少上述內(nèi)容,如下 Promise 鏈
是的。
為什么輸出不符合預(yù)期?
因?yàn)槌兄Z“鏈條”斷了。為了正確鏈接,您需要將回調(diào)函數(shù)傳遞給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));
添加回答
舉報(bào)