首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Promise.resolve

Promise.resolve(value)方法返回一个以给定值解析后的Promise对象。但如果这个值是个thenable(即带有then方法),返回的promise会“跟随”这个thenable的对象,采用它的最终状态(指resolved/rejected/pending/settled);否则以该值为成功状态返回promise对象。

语法

代码语言:javascript
复制
Promise.resolve(value);
Promise.resolve(promise);
Promise.resolve(thenable); 

参数

value用来解析待返回promise对象的参数。既可以是一个promise对象,也可以是一个thenable。

返回值

一个Promise是与给定值解决,或promise为值传递,如果该值是一个promise对象。

描述

静态方法Promise.resolve返回一个promise对象,这个promise对象是被解析后(resolved)的。

示例

使用静态方法Promise.resolve

代码语言:javascript
复制
Promise.resolve('Success').then(function(value) {
  console.log(value); // "Success"
}, function(value) {
  // not called
});

对一个数组进行resolve

代码语言:javascript
复制
var p = Promise.resolve([1,2,3]);
p.then(function(v) {
  console.log(v[0]); // 1
});

Resolve另一个promise对象

代码语言:javascript
复制
var original = Promise.resolve(33);
var cast = Promise.resolve(original);
cast.then(function(value) {
? console.log('value: ' + value);
});
console.log('original === cast ? ' + (original === cast));

// logs, in order:
// original === cast ? true
// value: 33

logs的倒序是由于then异步调用处理程序的缘故。看看then在这里如何运行。

resolve thenable的对象们并抛出错误

代码语言:javascript
复制
// 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.log(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
});

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Promise.resolve' in that specification.

Standard

Initial definition in an ECMA standard.

ECMAScript Latest Draft (ECMA-262)The definition of 'Promise.resolve' in that specification.

Living Standard

?

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

32.0

(Yes)

29.0

No

19

7.1

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

4.4.4

32.0

(Yes)

29

No

(Yes)

8.0

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com