标签:
其实, Promise就是一个类,而且这个类已经成为ES6的标准,是 ECMAScript 6 规范的重要特性之一。这个类目前在chrome32、Opera19、Firefox29以上的版本都已经支持了,要想在所有浏览器上都用上的话就看看es6-promise吧。
ES6 的 Promises 是采用了 Promises/A+ 提案的一种实现。你现在能够找到的各种第三方实现,如果是完全兼容了 Promises/A+ 的,那么就和 ES6 的 Promises 是一致的(当然了,第三方实现可能会增加更多的 API,而 ES6 的实现只需要符合 Promises/A+ 提案的最基本要求即可)。目前, 当然,也有一些第三方内库实现了该功能,如: Q 、 when 、 WinJS 、 RSVP.js 等。
另外说句 Promise 在JQuery中 就是 $.Deferred 作为新特性首次出现在版本1.5中,
function fn1(){
console.info("this is 1") ;
}
function fn2(){
console.info("this is 2");
}
function fn3(){
console.info("this is 3") ;
}
//按照顺序调用
fn1() ;
fn2() ;
fn3() ;
//输出的结果:
//this is 1
//this is 2
//this is 3
其实这样这做并不能保证fn1、fn2、fn3按照顺序的去执行的。大家都知道,javascritp是单线程执行的.假设
function fn1(){
setTimeout(function(){
console.info("this is 1") ;
},5000);
}
结果就不一定 按照顺序来了。按照异步的话,后面的 fn2 fn3的都得 写在f1的 setimeout 里面 。如果 复杂点 ,就会 不停地嵌套;如果解决
让输出的结果还是按照fn1->fn2->fn3的顺序去执行呢?
function fn1(){
var p = new Promise() ;
setTimeout(function(){
console.info("this is 11") ;
p.resolve() ;
},2000);
return p ;
}
function fn2(){
var p = new Promise() ;
console.info("this is 22") ;
p.resolve() ;
return p ;
}
function fn3(){
var p = new Promise() ;
console.info("this is 33") ;
p.resolve() ;
return p ;
}
//输出的结果是:
//this is 11
//this is 22
//this is 33
假如我们要显示某一个页的10条记录,但是我们只有一个通过id获取记录的接口,这样我们就需要发送10个请求,并且所有请求都完成之后再将记录全部添加到页面之中,Promise在这个场景下使用是特别合适的
// ids要获取信息的所有记录id
// getRecordById获取记录的接口,返回promise
Promise.all(ids.map(getRecordById))
.then(showRecords)
.catch(function (e) {
console.log(e);
});
或者 组件 下拉刷新,下拉刷新中,等到所有 ajax请求(别的请求)完毕以后,下拉刷新状态完成;才关闭刷新;
Promise.all([ajaxfn1, ajaxfn2, ajaxfn3]).then(function (results) {
console.log("success")
console.log(results);
}).catch(function(r){
console.log("err");
console.log(r);
});

Promise 对象用来进行延迟( deferred )和异步( asynchronous )计算.。一个 Promise 处于以下四种状态之一:
pending: 还没有得到肯定或者失败结果,进行中
fulfilled: 成功的操作
rejected: 失败的操作
settled: 已被 fulfilled 或 rejected
Promise 对象有两个重要的方法,一个是 then ,另一个是 resolve :
then:将事务添加到事务队列中
resolve:开启流程,让整个操作从第一个事务开始执行
(1)对象的状态不受外界影响。Promise 对象代表一个异步操作,有三种状态:Pending(进行中)、Resolved(已完成,又称 Fulfilled)和 Rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态。这也是 Promise 这个名字的由来,它的英语意思就是「承诺」,表示其他手段无法改变。
(2)一旦状态改变,就不会再变,任何时候都可以得到这个结果。Promise 对象的状态改变,只有两种可能:从 Pending 变为 Resolved 和从 Pending 变为 Rejected。只要这两种情况发生,状态就凝固了,不会再变了,会一直保持这个结果。就算改变已经发生了,你再对 Promise 对象添加回调函数,也会立即得到这个结果。这与事件(Event)完全不同,事件的特点是,如果你错过了它,再去监听,是得不到结果的。
var promise = new Promise(function(resolve, reject) { if (/* 异步操作成功 */){ resolve(value); } else { reject(error); } }); promise.then(function(value) { // success }, function(value) { // failure });
Promise 构造函数接受一个函数作为参数,该函数的两个参数分别是 resolve 方法和 reject 方法。
如果异步操作成功,则用 resolve 方法将 Promise 对象的状态,从「未完成」变为「成功」(即从 pending 变为 resolved);
如果异步操作失败,则用 reject 方法将 Promise 对象的状态,从「未完成」变为「失败」(即从 pending 变为 rejected)。
大体框架原理如下
var Promise = function() {
this.callbacks = [];
}
Promise.prototype = {
constructor: Promise,
resolve: function(result) {
this.complete("resolve", result);
},
reject: function(result) {
this.complete("reject", result);
},
complete: function(type, result) {
while (this.callbacks[0]) {
this.callbacks.shift()[type](result);
}
},
then: function(successHandler, failedHandler) {
this.callbacks.push({
resolve: successHandler,
reject: failedHandler
});
return this;
}
}
测试代码
// test
var promise = new Promise();
var delay1 = function() {
setTimeout(function() {
promise.resolve(‘数据1‘);
}, 1000);
return promise;
};
var callback1 = function(re) {
re = re + ‘数据2‘;
console.log(re);
promise.resolve(re);
};
var callback2 = function(re) {
console.log(re + ‘数据3‘);
};
delay1().then(callback1).then(callback2);
实际中用于生产环境,这是不够的;
如何实现Promise http://liuwanlin.info/shi-xian-promise/
Javascript 中的神器——Promise http://www.jianshu.com/p/063f7e490e9a
推荐的 Primise 插件 https://github.com/stefanpenner/es6-promise
推荐这篇文章 https://www.promisejs.org/implementing/
美团的剖析 Promise 之基础篇 http://tech.meituan.com/promise-insight.html
Promises/A+ https://promisesaplus.com/
MDN-Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
标签:
原文地址:http://www.cnblogs.com/surfaces/p/5650285.html