构造函数

new Promise(function(resolve, reject){});

构造函数接受一个函数(executor)作为参数,该函数在返回 Promise 实例之前被调用。函数的两个参数分别是 resolve 和 reject 函数。

如果 executor 函数执行中抛出异常,则 Promise 视为 rejected。

executor 函数返回值没有意义。

类方法

Promise.all(iterable)

类似于 jQuery.when() 方法,只有 iterable 中所有的 Promise 都被 resolve,它返回一个新的被 resolve 的 Promise,resolved 值为 iterable 中所有 resolved 值组成的数组;或者 iterable 中只要有一个 Promise 被 reject,则立刻返回一个新的被 reject 的 Promise,rejected 值同时传递给新的 Promise。

Promise.race(iterable)

一旦 iterable 中任何一个 Promise 被 resolve 或 reject,则立即返回一个新的被 resolve 或 reject 的 Promise。

Promise.reject(reason)

返回一个 rejected Promise。

Promise.resolve(value)

返回一个新的 Promise。如果 value 是一个 thenable 对象(Promise),新 Promise 状态与 thenable 一致;否则新 Promise 状态为 resolved,Promise 结果为 value。

实例方法

Promise.prototype.catch(onRejected)

返回一个新的 Promise。Promise 将 rejected 值视为一个 error,通过 catch 方法可以捕捉 rejected 值,并将该值传递给 onRejected 函数。onRejected 函数返回值将作为新 Promise 的 resolve 参数,也就是说,如果 onRejected 返回值是一个 Promise,则新 Promise 与该 Promise 状态一致;否则新 Promise 状态为 resolved,结果值为 onRejected 返回值。

如果一个 rejected Promise 没有调用过 catch 方法,在谷歌浏览器控制台会输出异常提示 Uncaught (in promise) 1

Promise.prototype.then(onFulfilled, onRejected)

返回一个新 Promise。如果 onFulfilled 和 onRejected 是函数,则使用它们的返回值作为新 Promise 的 resolve 参数。否则新 Promise 与旧 Promise 状态保持一致。

then 与 catch

虽然 then 方法可以分别处理 resolution 和 rejection 两种情景,但 ES6 Promise 将 rejection 更多地视作异步异常情景,因此提供 catch 方法处理 rejection 情景。

所以好的实践是使用 then 方法处理 resolution,catch 方法处理 rejection。

// 不推荐
asyncRun().then(function(value) {}, function(error) {}); // 推荐
asyncRun().then(function(value){}).catch(function(rejected) {});

尤其当需要链接多个 Promise 时,使用 then + catch 模式会让代码更加清晰。

// 不推荐
asyncRun()
.then(function(value) {}, function(error) {})
.then(function(value) {}, function(error) {})
.then(function(value) {}, function(error) {}); // 推荐
asyncRun()
.then(function(value){})
.then(function(value){})
.then(function(value){})
.catch(function(rejected) {});

Deferred 对象

ES6 取消了 Deferred 对象,鼓励直接使用 Promise,而且主张 Promise 应该由它的创建者来 resolve 或 reject。

但某些场景下,Deferred 对象仍然是一种更好的选择,尤其是 Promise 创建者与求值者分属不同对象时。

基于 ES6 Promise 实现的 Deferred 对象

简洁版:

function Deferred() {
var self = this;
var promise = this.promise = new Promise(function(resolve, reject) {
self.resolve = resolve;
self.reject = reject;
});
this.then = this.promise.then.bind(promise);
this.catch = this.promise.catch.bind(promise);
this.catch(function() {});
}

完整版:

/*
* @Author: laixi
* @Date: 2016-11-18 11:40:06
* @Last Modified by: laixi
* @Last Modified time: 2016-11-18 12:36:26
*/
var Deferred = function(beforeStart) {
if (!(this instanceof Deferred)) {
return new Deferred(beforeStart);
} var _resolve; // resolve function
var _reject; // reject function
var _result; // resolved value or rejected reason
var _state = 'pending'; // promise status
var doneCallbacks = [];
var failCallbacks = [];
var alwaysCallbacks = []; // create promise object
var promise = new Promise(function(resolve, reject) {
_resolve = resolve;
_reject = reject;
}); // eliminate annoying error prompt at Chrome console
promise.catch(function() {}); // respectively call callbacks in done callback queue or fail callback queue
promise.then(function(value) {
_result = value;
while (doneCallbacks.length > 0) {
var callback = doneCallbacks.splice(0, 1)[0];
callback.call(promise, value);
}
}, function(reason) {
_result = reason;
while (failCallbacks.length > 0) {
var callback = failCallbacks.splice(0, 1)[0];
callback.call(promise, reason);
}
}); // extend promise by adding done, fail, always.
// ---------------------------------------------- promise.done = function(callback) {
if (typeof callback === 'function') {
if (_state === 'resolved') {
callback.call(promise, _result);
} else {
doneCallbacks.push(callback);
}
}
return promise;
}; promise.fail = function(callback) {
if (typeof callback === 'function') {
if (_state === 'rejected') {
callback.call(promise, _result);
} else {
failCallbacks.push(callback);
}
}
return promise;
}; promise.always = function(callback) {
if (typeof callback === 'function') {
if (_state === 'pending') {
alwaysCallbacks.push(callback);
} else {
callback.call(promise, _result);
}
}
return promise;
}; this.promise = function() {
return promise;
}; this.state = function() {
return _state;
}; this.resolve = function(value) {
_state = 'resolved';
_resolve.call(promise, value);
}; this.reject = function(reason) {
_state = 'rejected';
_reject.call(promise, reason);
}; this.catch = promise.catch.bind(promise);
this.then = promise.then.bind(promise);
this.done = promise.done.bind(promise);
this.fail = promise.fail.bind(promise);
this.always = promise.always.bind(promise); if (typeof beforeStart === 'function') {
beforeStart.call(this, this);
}
};

ES6 Promise 接口的更多相关文章

  1. 如何把 Callback 接口包装成 Promise 接口

    最近一段时间一直在看Node.js,在开发过程中经常要调用一些异步接口,通常在接口的最后一个参数会传入一个回调函数,可以用来处理异常,非异常情况.大致模式如下: var fs = require(“f ...

  2. 通过 ES6 Promise 和 jQuery Deferred 的异同学习 Promise

    Deferred 和 Promise ES6 和 jQuery 都有 Deffered 和 Promise,但是略有不同.不过它们的作用可以简单的用两句话来描述 Deffered 触发 resolve ...

  3. ES6 Promise 全面总结

    转载:点击查看原文 ES6 Promise对象 ES6中,新增了Promise对象,它主要用于处理异步回调代码,让代码不至于陷入回调嵌套的死路中. @-v-@ 1. Promise本质 Promise ...

  4. 微信小程序Http高级封装 es6 promise

    公司突然要开放微信小程序,持续蒙蔽的我还不知道小程序是个什么玩意. 于是上网查了一下,就开始着手开发..... 首先开发客户端的东西,都有个共同点,那就是  数据请求! 看了下小程序的请求方式大概和a ...

  5. Es6 Promise 用法详解

     Promise是什么??    打印出来看看  console.dir(Promise) 这么一看就明白了,Promise是一个构造函数,自己身上有all.reject.resolve这几个眼熟的方 ...

  6. ES6 Promise 异步操作

    最近越来越喜欢与大家进行资源分享了,并且及时的同步到自己的园子内,为什么呢? 一.小插曲(气氛搞起) 在上个月末,由于领导的高度重视(haha,这个高度是有多高呢,185就好了),走进了公司骨干员工的 ...

  7. 解析ES6 Promise

    ES6 Promise 概念之类的,大概读者都应该有所知道,接下来我们直入终点. 先让我们来看看什么是Promise吧,他是一个object,类,arry,function? 首先,学习它的时候应该讲 ...

  8. jquery Promise和ES6 Promise的区别

    1. Deferred对象有resolve和reject方法,可以直接修改状态 jquery用Deferred实现了Promise规范,Deferred与ES6 Promise的最大区别是: Defe ...

  9. ES6 Promise对象then方法链式调用

    then()方法的作用是Promise实例添加解决(fulfillment)和拒绝(rejection)状态的回调函数.then()方法会返回一个新的Promise实例,所以then()方法后面可以继 ...

随机推荐

  1. 详解Bootstrap按钮组件

    按钮组也是一个独立的组件,所以可以找到相应的源码文件: Less:buttons.less Sass:_buttons.scss Css:Bootstrap.css    3131行~3291行 按钮 ...

  2. hashcode详解

    序言 写这篇文章是因为在看hashMap源码时遇到有什么hashcode值,然后就去查,脑袋里面是有映像的,不就是在Object中有equals和hashcode方法嘛,这在学java基础的时候就遇到 ...

  3. 删除配置文件解决OS X各种WiFi无法连接的顽固问题,解决MAC无法连接wif的情况 Preferences

    删除配置文件解决OS X各种WiFi无法连接的顽固问题 删除配置文件解决OS X各种WiFi无法连接的顽固问题1 记住现在wifi的密码并将wifi关闭2 前往文件夹/Library/Preferen ...

  4. Apex Design Patterns

    Apex allows you to build just about any custom solution on the Force.com platform. But what are the ...

  5. 工作组环境下管理windows.

    此处指的是windows7 1.防火墙设置 开启wmi,remote admin,防火墙远程管理 可以使用命令行 netsh advfirewall export "C:\temp\WFco ...

  6. Spring MVC3返回JSON数据中文乱码问题解决(转)

    Spring MVC3返回JSON数据中文乱码问题解决 查了下网上的一些资料,感觉比较复杂,这里,我这几使用两种很简单的办法解决了中文乱码问题. Spring版本:3.2.2.RELEASE Jack ...

  7. P2P资料

    常用链接 openstack创建实例的方法 http://www.cnblogs.com/popsuper1982/p/3800426.html qemu官网 http://wiki.qemu.org ...

  8. java 反射: 当Timestamp类型的属性值为null时,设置默认值

    import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Metho ...

  9. TextBox 文本框水印文字

    #region TextBox 文本框水印文字 /// <summary> /// 基于.NET 2.0的TextBox工具类 /// </summary> public st ...

  10. LeetCode: Lowest Common Ancestor of a Binary Search Tree 解题报告

    https://leetcode.com/submissions/detail/32662938/ Given a binary search tree (BST), find the lowest ...