在线文档教程

Promise.resolve

Promise.resolve

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

语法

Promise.resolve(value Promise.resolve(promise Promise.resolve(thenable

参数

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

返回值

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

描述

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

示例

使用静态方法Promise.resolve

Promise.resolve('Success').then(function(value) { console.log(value // "Success" }, function(value) { // not called }

对一个数组进行resolve

var p = Promise.resolve([1,2,3] p.then(function(v) { console.log(v[0] // 1 }

Resolve另一个promise对象

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的对象们并抛出错误

// 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 }

规范

SpecificationStatusComment
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Promise.resolve' in that specification.StandardInitial definition in an ECMA standard.
ECMAScript Latest Draft (ECMA-262)The definition of 'Promise.resolve' in that specification.Living Standard

浏览器兼容性

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic Support32.0(Yes)29.0No197.1

FeatureAndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic Support4.4.432.0(Yes)29No(Yes)8.0