
创建确定的Promise
由于 Promise 执行器的动态特性,Promise 构造函数是创建不确定的 Promise 的最佳方式。但是如果你想要一个 Promise 来表示一个先前计算的值,那么创建一个简单地将值传递给 resolve() 或 reject() 函数的执行器是没有意义的。 相反,有两种方法可以在给定特定值的情况下创建已确定的 Promise。
使用Promise.resolve
Promise.resolve() 方法接受一个参数并返回一个处于已完成状态的 Promise。这意味着如果您已经知道该 Promise 的值,则无需提供执行程序。 例如:
const promise = Promise.resolve(42);
promise.then(value => {
console.log(value); // 42
});
此代码创建一个fullfilment的promise,因此fullfilment handler接收 42 作为值。与本章中的其他示例一样,执行处理程序在当前脚本作业完成后作为微任务执行。 如果将拒绝处理程序添加到此 Promise 中,则永远不会调用拒绝处理程序,因为 Promise 永远不会处于拒绝状态。
如果你将一个 Promise 传递给 Promise.resolve(),那么该函数会返回你传入的相同 Promise。例如
const promise1 = Promise.resolve(42);
const promise2 = Promise.resolve(promise1);
console.log(promise1 === promise2);
使用Promise.reject
您还可以使用 Promise.reject() 方法创建被拒绝的 Promise。 这与 Promise.resolve() 类似,只是创建的 Promise 处于拒绝状态,如下所示:
const promise = Promise.reject(42);
promise.catch(reason => {
console.log(reason); // 42
});
添加到此promise的任何其他rejection handler都将被调用,但fullfilment handler不会,因为promise永远不会处于fullfiled状态。
Non-Promise Thenables
Promise.resolve() 和 Promise.reject() 也接受 non-promise thenables 作为参数。 当传递一个非承诺 thenable 时,这些方法会创建一个新的承诺,在 then() 函数之后调用
当一个对象有一个 then() 方法接受一个 resolve 和一个 reject 参数时,就会创建一个 non-promise thenable,像这样:
const thenable = {
then(resolve, reject) {
resolve(42);
}
};
此示例中的 thenable 对象除了 thethen() 方法之外没有与 Promise 关联的特征。 您可以调用 Promise.resolve() 将 thenable 转换为fillfiled的Promise:
const thenable = {
then(resolve, reject) {
resolve(42);
}
};
const promise = Promise.resolve(thenable);
promise.then(value => {
console.log(value); // 42
});
在这个例子中,Promise.resolve() 调用 thenable.then() 以便可以确定一个 promise 状态。由于在 then() 方法中调用了 resolve(42),所以实现了 thenable 的 promise 状态。一个名为 promise 的新 promise 以 thenable 传递的值(即 42)在已完成状态下创建,promise 的执行处理程序接收 42 作为值.
Promise.resolve() 可以使用相同的过程从 thenable 创建一个被拒绝的 Promise:
const thenable = {
then(resolve, reject) {
reject(42);
}
};
const promise = Promise.resolve(thenable);
promise.catch(value => {
console.log(value); // 42
});
此示例与上一个示例类似,只是 thenable 被拒绝。 当 thenable.then() 执行时,会在拒绝状态下创建一个新的 Promise,其值为 42。然后将该值传递给 Promise 的拒绝处理程序。
Promise.resolve() 和 Promise.reject() 像这样工作,让您可以轻松地使用 non promise thenables。 在 2015 年引入 Promise 之前,许多库都使用了 thenables,因此将 thenables 转换为正式 Promise 的能力对于向后兼容先前存在的库非常重要。 当您不确定一个对象是否是一个 Promise 时,通过 Promise.resolve() 或 Promise.reject() 传递该对象(取决于您的预期结果)是最好的找出方法,因为 Promise是不可改变的。