前端异步方案-Promise

背景:ajax请求如果出现callback嵌套,会造成不利于代码阅读,这就是我们常说的毁掉地狱。ECMAscript6 为开发者提供了Promise对象。

Promise的三种状态

  1. Pending 创建Promise对象实例的初始化状态
  2. Fulfilled 成功回调状态。在链式then方法执行resolve
  3. Rejected 失败回调状态。在链式catch方法中执行reject

    基于Promise封装ajax请求模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function ajax(url) {
return new Promise(function (resolve,reject) {
var xml = new XMLHttpRequest()
xml.open('GET', url, true);
xml.send(null);
xml.onreadystatechange = function () {
if (xml.readyState === 4) {
if (xml.status === 200) {
// 请求成功
resolve(xml.responseText)
} else {
reject(new Error('请求失败状态码:'+ xml.status))
}
}
}
})
}

ajax('http://www.xxxx.com').then(res-0 =>{
console.log(res-0)
return ajax('http://www.ccc.com')
}).then(res-1 =>{
console.log(res-1)
}).catch(err =>{
console.log(err)
})

Promise API

Promise.all

Promise.race

原生javascript实现Promise

参考mdn jquery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module.exports = {
defered() {
var _success, _error;
return {
resolve(res) {
_success(res)
},
reject(err) {
_error(err)
},
promise: {
then(success, error){
_success = success
_error = error
}
}
}
}
}

promise

  1. blusbird实现promise标准,兼容浏览器
  2. jquery deferred
  3. promiseaplus