Promise.resolve(value)
方法返回一个由 给定的value 决议的Promise对象。
如果value的值为promise,返回这个promise;
如果value的值是thenable(即,带有then方法的对象),返回的Promise对象的最终状态由then方法执行决定;
否则的话(即value为 空,基本类型或者不带then方法的对象),返回的Promise对象状态为fulfilled,并且将该value传递给对应的then方法。
先看看简单的例子:
Promise.resolve("Success").then(function(value) {
console.log(value); // "Success"
}, function(value) {
// 不会被调用
});
语法
Promise.resolve(value);
参数:value 是将被Promise对象resolve的参数。value 也可以是一个Promise对象,或者是一个thenable。(Argument to be resolved by this Promise. Can also be a Promise or a thenable to resolve.)
举例一:resolve是另外一个promise对象
let original = Promise.resolve('happy chen');
let cast = Promise.resolve(original);
cast.then((val) => {
console.log(val);
})
console.log(`original === cast ? ${original === cast}`);
// original === cast ? true
// happy chen
这里由于 异步地 调用then 方法,所以 有一个同步异步先后执行的区别
举例二:Resolve一个thenable对象
let p1 = Promise.resolve({
then: function (onFulfill, onReject) { onFulfill('fulfilled') }
});
console.log(p1 instanceof Promise);
p1.then(v => {
console.log(v);// "fulfilled"
},(e)=>{
// not called
})
// true
// fulfilled
返回值:返回一个resolve过带着给定值的Promise对象,如果参数是一个Promise对象,则直接返回这个Promise对象。(见上面 举例一)
其它的例子:resolve一个数组
let p = Promise.resolve(['happy','chen',666]);
p.then(function(v){
console.log(v[2]);
})
// 666
resolve thenable 并抛出错误:
// Resolving a thenable object
var p1 = Promise.resolve({
then: function(onFulfill, onReject) { onFulfill('fulfilled!'); }
});
console.log(p1 instanceof Promise) // true, object casted to a Promise
p1.then(function(v) {
console.log(v); // "fulfilled!"
}, function(e) {
// not called
});
// Thenable throws before callback
// Promise rejects
var thenable = { then: function(resolve) {
throw new TypeError('Throwing');
resolve('Resolving');
}};
var p2 = Promise.resolve(thenable);
p2.then(function(v) {
// not called
}, function(e) {
console.error(e); // TypeError: Throwing
});
// Thenable throws after callback
// Promise resolves
var thenable = { then: function(resolve) {
resolve('Resolving');
throw new TypeError('Throwing');
}};
var p3 = Promise.resolve(thenable);
p3.then(function(v) {
console.log(v); // "Resolving"
}, function(e) {
// not called
});