實現值
該 Promise.resolve
靜態方法可以用來值包裝成承諾。
let resolved = Promise.resolve(2);
resolved.then(value => {
// immediately invoked
// value === 2
});
如果 value
已經是一個承諾, Promise.resolve
只是重鑄它。
let one = new Promise(resolve => setTimeout(() => resolve(2), 1000));
let two = Promise.resolve(one);
two.then(value => {
// 1 second has passed
// value === 2
});
事實上,value
可以是任何可以的(定義 then
方法的物件,其工作方式與規範相容的承諾一樣)。這允許 Promise.resolve
將不受信任的第三方物件轉換為受信任的第一方 Promises。
let resolved = Promise.resolve({
then(onResolved) {
onResolved(2);
}
});
resolved.then(value => {
// immediately invoked
// value === 2
});
該 Promise.reject
靜態方法返回一個承諾,其立即與給定 reason
拒絕。
let rejected = Promise.reject("Oops!");
rejected.catch(reason => {
// immediately invoked
// reason === "Oops!"
});