ES6 Promise

当我们使用ajax时,异步回调,当请求过多时,很容易形成回调地域。使我们很难维护,不易拓展功能和管理。在jQuery中实现里管理异步回调deferred,同样,ES6原生的js也提供了管理异步回调的方法。使其能线性的拓展,方便我们管理和维护。

Promise是ES6内置的构造函数,使用时要使用new创建一个promise对象。接收一个函数作为参数。这个函数里面的代码是同步执行的。

promise有三个状态,pending:初始状态。fulfilled 成功状态 。rejected 失败状态。

当在传入的函数里执行某些操作时,我们可以触发他的成功,或失败状态。成功执行某些操作。失败执行某些操作。这些操作在then方法里面承诺。

then 方法传入两个参数函数,分别对应着成功的回调函数和失败的回调函数。并且在then中注册的函数是异步执行的,及会放在任务队列中,等主任务执行完毕在执行,但是会陷入settimeout,setInterval等异步任务,(任务队列的任务分为主任务和微任务,微任务会先入主任务执行)。  因此下方的代码执行时0 2 1。

then方法返回一个新的promise对象。这提供了链式调用,是异步任务可以线性的方式书写。

     let oP = new Promise((resolve,reject)=>{
            //setTimeout(() => {
             //   Math.random() * 100 > 60 ? resolve('ok') : reject('no');  i
           // }, 1000);
            console.log(0);
            resolve(1);
            console.log(2);
        }) 

     oP.then((val)=>{ console.log(val); return new Promise((res,rej)=>{ rej(2); }); }).then(function(val){ console.log(val); },function(reason){ console.log(reason); })

then的链式调用。当触发第一个then的成功函数(第一个函数没有抛出错误)后会调用第二个then的成功函数。并且return的返回值会作为第二个回调函数的参数。

     let oP = new Promise((resolve,reject)=>{
            resolve(1);
        })    
       
        oP.then((val)=>{
            console.log('ok' + val);
        //throw new Error('error');
       return val;
        },function(reason){
            console.log('no' + reason);
       return val; }).then(function(val){ console.log('ok' + val); },function(reason){ console.log('no' + reason); })

    // 1 OK
// 1 OK

当触发第一个函数抛出错误时,会调用第二个then函数的失败函数,捕获错误。

在两个then之间存在空then时,会直接忽视,仍然会获取到上一个函数的参数。

promise.all([]),参数接收一个(可迭代带有iterator属性的就是可迭代的)promise对象数组,当所有promise对象都成功就返回一个结果数组,当有一个失败,就调用失败函数,返回最先被reject失败状态的值,执行后返回一个新的promise实例。

    function text(x){
            return new Promise((res,rej)=>{
                setTimeout(() => {
                    Math.random() * 100 > 50 ? res(x) : rej(x);             
                }, 100);
            })
        }

        let oP = Promise.all([text(),text(),text()]);
        oP.then(function(val){
            console.log(val);
        },(reason)=>{
            console.log(reason);
        })

promise.race([]),参数接收一个promise数组,当那个promise对象结果或得的快,就返回那个最快的结果。

     let oP = Promise.race([text('a'),text('b'),text('c')]);
        oP.then(function(val){
            console.log(val);
        },(reason)=>{
            console.log(reason);
        })
原文地址:https://www.cnblogs.com/jiaobaba/p/11967760.html