ES6 Promise 的链式调用

1.什么是Promise

Promise 对象代表了未来将要发生的事件,用来传递异步操作的消息。

2、对象的状态不受外界影响。Promise 对象代表一个异步操作,有三种状态:

  • pending: 初始状态,不是成功或失败状态,执行中的状态
  • fulfilled: 意味着操作成功完成。
  • rejected: 意味着操作失败。

3.Promise 创建

new Promise(function(resolve, reject){   //异步处理  执行完成后调用resolve  执行失败调用 reject

  setTimeout(function(){

    resolve();  //   

  },2000)

})

eg:

new Promise((resolve,reject)=>{   

 setTimeout(function(){

    resolve();  //   

  },2000)

}).then(function(r){

  //这里执行的就是resolve方法

  console.log('AAAAA')

})

4.Promise 的链式调用

Promise 对象的then 函数 中可以继续返回Promise对象  这个对象可以继续执行then方法

eg:

new Promise((resolve,reject)=>{  
 setTimeout(function(){
    resolve(); //
  },2000)
}).then(function(r){
  //这里执行的就是resolve方法
  console.log('AAAAA');
return new Promise((resolve,reject)=>{  

 setTimeout(function(){
    resolve(); //
  },2000)
});
}).then((c,d)=>{
console.log('BBBBB')
})

 效果:

 

原文地址:https://www.cnblogs.com/yaoweijun/p/14875859.html