实现值

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!"
});