Promise() 构造器
Promise
构造器主要用于包装不支持promise(返回值不是Promise
)的函数。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
交互式的demo的源码在GitHub仓库,如果你乐于为交互式的demo做贡献,请克隆https://github.com/mdn/interactive-examples并提交pull request .
语法
new Promise(executor)
参数
executor
- 这是一个双参函数,参数为
resolve和reject
。Promise
的实现会立即执行executor
,并传入resolve和reject
函数(Promise
构造器将会在返回新对象之前executor
)。当resolve
和reject
函数被调用时,它们分别对promise执行resolve
和reject
。executor
通常会触发一些异步运算,一旦运算成功完成,则resolve
掉这个promise,如果出错则reject
掉。如果executor
函数执行时抛出异常,promise状态会变为rejected
。executor
的返回值也会被忽略。
例子
我们通过new
关键字和Promise
构造器创建它的对象。这个构造器接受一个名为"executor function"的函数。这个函数应当接受两个函数参数。当异步任务成功时,第一个函数(resolve
)将被调用,并返回一个值代表成功。当其失败时,第二个函数(reject
)将被调用,并返回失败原因(失败原因通常是一个error对象)。
const myFirstPromise = new Promise((resolve, reject) => {
// do something asynchronous which eventually calls either:
//
// resolve(someValue) // fulfilled
// or
// reject("failure reason") // rejected
});
为了提供一个拥有promise功能的函数,简单的返回一个promise即可:
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open("GET", url)
xhr.onload = () => resolve(xhr.responseText)
xhr.onerror = () => reject(xhr.statusText)
xhr.send()
});
}
说明
Specification |
---|
ECMAScript (ECMA-262) Promise constructor |
浏览器兼容性
BCD tables only load in the browser