2 回答

TA貢獻1966條經(jīng)驗 獲得超4個贊
如果你跑
function get1() {
return new Promise((r)=>setTimeout(() => r(),3000))
}
function rejection() {/*Handle rejection*/}
function doAll(...ps) {
return Promise.all(ps.map(rejection))
}
(async () => {
var p1 = get1().then(()=>console.log("1"));
var p2 = get1().then(()=>console.log("2"));
Promise.all([p1, p2]).then(()=>{
console.log("3")
})
})()
那么結(jié)果是正確的
1
2
3
If you run
function get1() {
return new Promise((r)=>setTimeout(() => r(),3000))
}
function rejection() {/*Handle rejection*/}
function doAll(...ps) {
return Promise.all(ps)
}
(async () => {
var p1 = get1().then(()=>console.log("1"));
var p2 = get1().then(()=>console.log("2"));
doAll(p1, p2).then(()=>{
console.log("3")
})
})()
然后你又得到正確的
1
2
3
結(jié)果,問題出在ps.map(rejection). 讓我們來看看:
function get1() {
return new Promise((r)=>setTimeout(() => r(),3000))
}
function rejection() {/*Handle rejection*/}
function doAll(...ps) {
console.log(ps);
console.log(ps.map(rejection));
return Promise.all(ps.map(rejection));
}
(async () => {
var p1 = get1().then(()=>console.log("1"));
var p2 = get1().then(()=>console.log("2"));
doAll(p1, p2).then(()=>{
console.log("3")
})
})()
輸出
兩個元素的數(shù)組,兩者都是undefined
微不足道的評估。因為ps.map(rejection)
是一個箭頭函數(shù),它命名它的參數(shù)為 rejection 并且不返回任何東西。

TA貢獻1804條經(jīng)驗 獲得超8個贊
如果你想在 javascript 中使用異步操作,你可以使用 3 種方法。
打回來
承諾
異步/等待
為了實現(xiàn)您想要的確切內(nèi)容,最好和優(yōu)化的方法是使用 async/await 方法。
你可以這樣做:
async function getAllData(){
? ? ? const p1 = await promise1;
? ? ? const p2 = await promise2;
? ? ? ?
? ? ? }
現(xiàn)在 getAllData 返回 Promise,您可以使用 .then() 獲取結(jié)果并使用 .catch() 獲取錯誤。
添加回答
舉報