异步的概念
单线程编程中,程序的运行是同步的(同步不意味着所有步骤同时运行,而是指步骤在一个控制流程中按顺序执行)。而异步的概念则是不保证同步的概念,也就是说,一个异步过程的执行将不再与原有的序列有顺序关系。简单来解释就是:同步按你的代码顺序执行,异步不按照代码顺序执行,异步的执行效率更高。
Promise 是一个ES6提供的类,目的是更加优雅地书写复杂的异步任务
1、Promise 对象代表一个异步操作,有三种状态:
padding(进行中)
fulfilled(已成功)
rejected(已失败)
2、Promise 构造函数接收一个函数作为参数,改函数的两个参数分别是 resolve 和 reject
3、一个 Promise 对象只能改变一次状态,成功或者失败都会返回结果数据。
4、then 方法可以接收两个回调函数作为参数,第一个回调函数时 Promise 对象的状态改变为 resoved 是调用,第二个回调函数是 Promise 对象的状态变为 rejected 时调用。其中第二个参数可以省略。
5、catch 方法,该方法相当于最近的 then 方法的第二个参数,指向 reject 的回调函数,另一个作用是,在执行 resolve 回调函数时,如果出错,抛出异常,不会停止运行,而是竟然 catch方法中。
注意:catch 只捕获最近的 then 的回调函数,前面的 then 的执行不成功的结果,有后面 then 的 reject 回调函数执行,如果没有后续 then 回调函数执行,则会被catch捕获执行。
Promise 基本用法
let promise1 = new Promise(function (resolve, reject){
setTimeout(function(){
resolve('ok') // 将这个 promise 置为成功状态 fulfilled, 会触发成功回调
},3000)
})
promise1.then(fucntion success(val){
console.log(val)
})
最简单代码实现一个Promise
class PromiseM{
constructor(process){
this.status = 'padding'
this.mag = ''
process(this.resolve.bind(this), this.reject.bind(this))
return this
}
resolve(val){
this.status = 'fulfilled'
this.msg = val
}
reject(err){
this.status = 'rejected'
this.msg = err
}
then(fulfilled, reject){
if(this.status === 'fulfilled'){
fulfilled(this.msg)
}
if(this.status === 'rejected'){
reject(this.msg)
}
}
}
var mm = new PromiseM(function(resolve,reject){
resolve('123')
})
mm.then(function(success){
console.log(success)
},function(){
console.log('fail')
})