自己捏一個 Promise

自己捏比較好懂。

簡述

直接看例子:

1
2
3
4
5
6
7
8
9
const mySuccessPromise = new Promise((resolve, reject) => {
resolve('Ya!!!!');
});
const myFailedPromise = new Promise((resolve, reject) => {
reject('No~~~~')
})

mySuccessPromise.then(data => console.log('data =', data));
myFailedPromise.catch(data => console.log('data =', data));

就跟在 fetch 裡講的一樣,resolve 代表成功,所以用 then 來拿到我們在 Promise 裡面寫的內容;而 reject 代表失敗,所以用 catch 來拿到內容。

當然,也可以利用回傳 Promise 的方式來寫在一起:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const mySuccessPromise = new Promise((resolve, reject) => {
resolve('Ya!!!!');
});
const myFailedPromise = new Promise((resolve, reject) => {
reject('No~~~~')
})

mySuccessPromise
.then(data => {
console.log('data =', data);
return myFailedPromise;
})
.catch(data => {
console.log('data =', data);
});
Promise 最大的用途? 用 Promise 來包裝 XMLHttpRequest
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×