普通的回调函数解决异步问题,如果多个异步就会产生回调地域的问题,commonjs社区首先提出了promise规范,表示一个任务的成功或失败。
是一个对象,异步调用,有几种状态分别是pending(待定)、fulfilled(成功)、rejected(失败)
pending: 待定状态,成功或失败状态。
fulfilled: 意味着操作成功完成。
rejected: 意味着操作失败。
onFuilled:成功回调
onRejected:失败回调
基本用法:
const promise = new Promise(function(resolve, reject) {
resolve(100)
// reject(new Error('promise reject'))
})
promise.then(function(res) {
console.log(res)
},function(error) {
console(error)
})
使用案例:(使用promise封装ajax)
function ajax (url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'
xhr.onload = function () {
if (this.status === 200) {
resolve(this.responseType)
} else {
reject(new Error(this.statusText))
}
}
xhr.send()
})
}
ajax('../api/user.json').then(function(res) {
console.log(res)
}, function(err) {
console.log(err)
})
promise的链式调用(尽可能保证异步任务的扁平化,避免回调嵌套)
--Promise对象的then方法会返回一个全新的Promise对象
后面的的then方法就是在为上一个then方法返回的Promise注册回调
前面then方法中回调函数的返回值会作为后面的then方法回调的参数
如果回调中返回的是Promise对象,那后面then方法的回调会等待它的结束
ajax('/api/user.json').then(function(res) {
console.log(111)
return ajax('/api/urls.json') // 没有返回值,返回的是undefined
}, function(err) {
console.log(err)
return ajax('/api/urls.json')
}).then(function(value) {
console.log(222)
return ajax('/api/urls.json')
}).then(function(value) {
console.log(333)
})..catch(function(error) {
console.log(err)
// 整个promise链上错误的捕捉
})
Reject和catch的区别
reject 是用来抛出异常,catch 是用来处理异常
reject 是 Promise 的方法,而 catch 是 Promise 实例的方法
reject后的东西,一定会进入then中的第二个回调,如果then中没有写第二个回调,则进入catch
网络异常(比如断网),会直接进入catch而不会进入then的第二个回调
Promise静态方法
Promise.resolve('1') // 将一个值快速的转化为promise对象
// 两者等价
Promise.resolve('foo')
.then(function(value) {
console.log(value)
})
new Promise(function(resolve, reject) {
resolve('foo')
})
var promise = ajax('/api/user.json')
var promise2 = Promise.resolve(promise)
console.log(promise === promise2) // true
thenable
Promise.resolve({
then: function (onFulfilled, onRejected) {
onFulfilled('foo')
}
}).then(function(value) {
console.log(value)
})
Promise.reject(new Error('rejected'))
.catch(function(error) {
console.log(error)
})
网友评论