Promise介绍与基本使用
Promise 是 ES6 引入的异步变成的新解决方案,语法上 Promise 是一个构造函数,用来封装异步操作并可以获取其成功或失败的结果。
- Promise 构造函数:
Promise(excutor) {}
Promise.prototype.then
方法Promise.prototype.catch
方法
// 实例化 Promise 对象
const p = new Promise(function(resolce, reject) {
setTimeout(function() {
// let data = "数据"
// 使用 resolve 将 Promise 的状态改变为成功,then 方法会调用第一个回调函数
// resolve(data)
// 使用 reject 将 Promise 的状态改变为失败,then 方法会调用第二个回调函数
let err = "失败"
reject(err)
}, 1000)
})
p.then(function(value) {
console.log(value) // 数据
}, function(reason) {
console.log(reason) // 失败
})
then方法返回的结果
then 方法的返回结果是 Promise 对象,对象状态由回调函数的执行结果决定
-
如果回调函数中返回的是非 Promise 类型的属性,则返回的 Promise 状态为成功,Promise 值 return 的值
const result = p.then(value => { return 123 }) console.log(result)
-
若回调函数中没有写 return,则返回的 Promise 状态为成功,值为 undefined
-
如果回调函数中返回的是一个 Promise 对象,则返回的 Promise 状态决定了 then 方法返回的 Promise 状态,then 方法返回的 Promise 值也是回调函数返回的 Promise 对象的值
const result = p.then(value => { return new Promise((resolve, reject) => { reject('error') }) })
-
若在回调函数中抛出错误,则返回的 Promise 状态为失败,值为 throw 后的值
const result = p.then(value => { throw new Error('出错了!') }) console.log(result)
catch方法
catch 方法其实可以看成是一个语法糖,可以使用 then 方法的第二个回调函数代替
const success = p.then(value => {
console.log(value)
})
const fail = p.catch(error => {
console.log(error)
})