Promise 常用api方法

Abby 旦旦
4 min readSep 12, 2021

--

Promise.all

Promise.all 是Promise裡面其中一個常用方法,會等所有結果完成後才會執行下個動作

all所帶入的是一個陣列,傳出的也會是一個陣列。

大多使用all的方法較多,在遠端抓資料的時候會抓多個api。

以下範例Promise.all會在最後一個陣列完成後,才執行 then 或 catch:

function promiseFn(num, time = 500) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (num) {
resolve(`成功 ${num}`);
} else {
reject('失敗');
}
}, time);
});
}
Promise.all([
promiseFn(1, 0),
promiseFn(2, 1000),
promiseFn(3, 2000) // 會等到這個執行完2秒後,再執行then
])

.then(res => {
console.log(res);
// 會得到 ['成功 1', '成功 2', '成功 3']
console.log(res[0], res[1], res[2]);
// 會得到 成功 1 成功 2 成功 3
})
.catch(res => {
console.log(res);
})

這邊要注意,只要Promise.all陣列中有一個出現錯誤,就會跳到 catch:

Promise.all([
promiseFn(1, 0),
promiseFn(0, 1000),
promiseFn(3, 2000)
])
.then(res => {
console.log(res);
console.log(res[0], res[1], res[2]);
})
.catch(res => {
console.log(res);
// 會得到 失敗
})

Promise.race

Promise.race是Promise裡面其中一個常用方法,會傳出第一個完成的結果

race所帶入的是一個陣列,傳出的只會是一個值,不是陣列

function promiseFn(num, time = 500) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (num) {
resolve(`成功 ${num}`);
} else {
reject('失敗');
}
}, time);
});
}
Promise.race([
promiseFn(1, 1000),
promiseFn(2, 500), // 因為秒數最少最先完成,所以只會執行這個,然後執行then
promiseFn(3, 2000)
])

.then(res => {
console.log(res); // 會得到 成功 2
console.log(res[0], res[1]); // 會得到 成 功
})
.catch(res => {
console.log(res);
})

這邊要注意,只有最先完成的值是被拒絕的才會跳到 catch:

Promise.race([
promiseFn(1, 1000),
promiseFn(0, 500), // 因為秒數最少最先完成,但是是被拒絕的,所以跳到catch
promiseFn(3, 2000)
])

.then(res => {
console.log(res);
console.log(res[0], res[1]);
})
.catch(res => {
console.log(res); // 會得到 失敗
})

如果不是最先完成的被拒絕,就不會影響結果:

Promise.race([
promiseFn(0, 1000), // 雖然被拒絕,但是不是第一個完成的
promiseFn(2, 500),
promiseFn(0, 2000) // 雖然被拒絕,但是不是第一個完成的
])

.then(res => {
console.log(res); // 會得到 成功 2
console.log(res[0], res[1]); // 會得到 成 功
})
.catch(res => {
console.log(res);
})

--

--

Abby 旦旦

從零開始轉職網頁設計,正在緩慢朝前端工程邁進中!偶爾會發一些讀後感和UI分享,ㄚㄚ!