ReactWeb前端之路让前端飞

Promise、async ,es6异步解决方案

2017-08-13  本文已影响213人  Dabao123

本文你将看到:

promise介绍以及用法
promise常用api
demo使用Promise实现一个简单axios
async方法

1.promise基本用法

Promise 是异步编程的一种解决方案。
从语法上说,Promise 是一个对象,从它可以获取异步操作的消息。
我们先通过一个例子来谈谈promise。

function dome(t) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, t, 'resolve');
  });
}
dome(1000).then((value) => {
  console.log(value);
})

Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。
resolve函数:将Promise对象的状态从“未完成”变为“成功”并将异步操作的结果,作为参数传递出去
reject函数:将Promise对象的状态从“未完成”变为“失败”,将异步操作报出的错误,作为参数传递出去。
下面我们为你说说,到底发生了什么:
当demo执行时,新建了一个promise实例,并且在t毫秒以后,执行resolve函数。即表示成功的函数。
then可以接受两个回调函数作为参数。第一个代表成功时调用,第二个代表失败时调用。
因为我们触发了resolve,并且返回‘resolve’,所以,出发了then第一个回调函数会打印value会打印出 resolve。
如果,promise实例即没有执行resolve也没有执行reject,则这两个回调函数都不会调用,例如

function dome(t) {
  return new Promise((resolve, reject) => {});
}
dome(1000).then((value) => {
   console.log(1);
},(value) => {
   console.log(2)
})

运行结果,将什么也不打印。


Paste_Image.png

如果调用resolve:

function dome(t) {
  return new Promise((resolve, reject) => {
     resolve('ok')
 });
}
dome(1000).then((value) => {
   console.log(value);
},(value) => {
   console.log(2)
})

结果为:

Paste_Image.png

如果调用reject:

function dome(t) {
  return new Promise((resolve, reject) => {
     reject('err')
 });
}
dome(1000).then((value) => {
   console.log(value);
},(err) => {
   console.log(err)
})

结果:

Paste_Image.png

那么promise的执行的先后顺序是如何呢?

let promise = new Promise((resolve, reject) => {
  console.log('p');
  resolve();
});
promise.then( () => {
   console.log('ok');
});
console.log('no');

结果:

Paste_Image.png

2.then方法的链式写法

promise实例调用then方法以后,返回的是一个新的promise实例。因此可以在then方法的后面继续调用then方法。
例如:

function dome(t) {
  return new Promise((resolve, reject) => {
      setTimeout(resolve, t, t*2);
 });
}
dome(1000).then( value => {
      return dome(value)
}).then( value => {
      console.log('sec'+value)
},err => {
      console.log('err'+err)
})

即结果为

Paste_Image.png

catch方法

Promise.prototype.catch方法是.then(null, rejection)的别名。

function dome(t) {
  return new Promise((resolve, reject) => {
      setTimeout(reject, t, '发生错误');
 });
}
dome(1000).catch( err=>  {
         console.log(err)
})

结果:

Paste_Image.png

如果Promise状态已经变成Resolved,再抛出错误是无效的。
并且Promise 对象的错误会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个catch语句捕获。
例如:

dome(1000).then( value => {
      return dome(value)
}).then( value => {
      console.log('sec'+value)
}).catch( err=>{})

上面代码中,一共有三个promise对象:一个由dome产生,两个由then产生。它们之中任何一个抛出的错误,都会被最后一个catch捕获。
所以建议使用catch方法,尽量不要用then方法的第二个参数,因为catch可以捕获到前面then方法中的错误。

all方法

Promise.all方法可以将多个 Promise 实例,包装成一个新的 Promise 实例。
在多个实例中,加入有一个实例被rejected,则新的实例就会变成rejected。
只有当所有实例状态都变成fulfilled,则新的实例状态才会变成fulfilled。
所有实例的返回值将组成一个数组,返回给新实例。
例如

function dome1() {
  return new Promise((resolve, reject) => {
      resolve('dome1')
 });
}
function dome2() {
  return new Promise((resolve, reject) => {
      resolve('dome2')
 });
}
function dome3() {
  return new Promise((resolve, reject) => {
      resolve('dome3')
 });
}
Promise.all([dome1(),dome2(),dome3()]).then((result) => {
    console.log(result)
}).catch(err => {
    console.log(err)
})

结果

Paste_Image.png

因为每个势力都是resolve 所以返回了包含每个实例返回值组成的数组。

function dome1() {
  return new Promise((resolve, reject) => {
      resolve('dome1')
 });
}
function dome2() {
  return new Promise((resolve, reject) => {
      reject('err2')
 });
}
function dome3() {
  return new Promise((resolve, reject) => {
      resolve('dome3')
 });
}
Promise.all([dome1(),dome2(),dome3()]).then((result) => {
    console.log(result)
}).catch(err => {
    console.log(err)
})

结果:

Paste_Image.png

第二个reject所以最终返回了 err

race

race和all方法类似,只不过在在逻辑上只要所有子实例中有一个状态发生改变,就会立马把状态传递给新的实例。在这里就不在写例子了。大家自己研究。
reject方法与reject方法

Promise.resolve('cxh')
// 等价于
new Promise(resolve => resolve('cxh'))

如果参数是Promise实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例。
如果参数是一个带有then方法的实例,Promise.resolve方法会将这个对象转为Promise对象,然后就立即执行该对象的then方法。
加入参数不是对象,则Promise.resolve方法返回一个新的Promise对象,状态为Resolved,Promise.resolve方法的参数,会同时传给回调函数。
例如

var p = Promise.resolve('cxh');
 p.then(function (s){
    console.log(s)
});

不带有任何参数则,Promise.resolve方法返回一个新的Promise对象,状态为Resolved。
Promise.reject()方法也会返回一个新的 Promise 实例,该实例的状态为rejected。

done方法

因为Promise内部的错误不会冒泡到全局,我们无法捕捉到抛出的错误怎么办?
所以提出一个done方法,在回调链末端,保证任何错误都能抛出。

Promise.prototype.done = function (fulfilled, rejected) {
  this.then(fulfilled, rejected)
    .catch(function (reason) {
      setTimeout(() => { throw reason }, 0);
    });
};

上面的方法很简单,就是给Promise添加一个done方法,在done方法内部,用this指向promise添加then和catch方法。

finally方法

finally方法用于指定不管Promise对象最后状态如何,都会执行的操作。

Promise.prototype.finally = function (callback) {
  let parmise = this.constructor;
  return this.then(
    value  => parmise.resolve(callback()).then(() => value),
    reason => parmise.resolve(callback()).then(() => { throw reason })
  );
};

demo实例

下面我们用promise写一个异步获取数据方法:

  class Axios {
    constructor(){}
    post(url){
        console.log(1)
        return this.getData(url,'POST')
    }
    get(url){
        console.log(2)
        return this.getData(url,'GET')
    }
    getData(url,methods){
        var promise = new Promise(function(resolve, reject){
            var client = new XMLHttpRequest();
            client.open(methods, url);
            client.onreadystatechange = handler;
            client.responseType = "json";
            client.setRequestHeader("Accept", "application/json");
            client.send();

            function handler() {
               if (this.readyState !== 4) {
                return;
               }
               if (this.status === 200) {
                  resolve(this.response);
               } else {
                  reject(new Error(this.statusText));
                }
            };
        });
        return promise;
    }
}

var axios = new Axios;
axios.get('http://localhost:3000/getData').then((value) => {
    console.log(value);
});
axios.post('http://localhost:3000/postData').then((value) => {
    console.log(value);
});
console.log("cxh")

node.js部分,我们使用express

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index');
});
router.get('/getData', function(req, res, next) {
  res.json({ "code": '100',"result":"get success!" });
});
router.post('/postData', function(req, res, next) {
  res.json({ "code": '100',"result":"post success!" });
});
module.exports = router;

下面是我们的运行结果:

Paste_Image.png

async 函数

async 函数只不过是Generator 函数的语法糖。
async函数就是将 Generator 函数的星号(*)替换成async,将yield替换成await,仅此而已。

  async function () {
        var res1 = await axios.get('http://localhost:3000/getData');
        var res2 = await axios.get('http://localhost:3000/getData?name='+res1');
       console.log(res1);
       console.log(res2);
};

当执行上面这段代码的时候,遇到await就会跳出,继续执行下面的代码,直到axios拿到数据,再继续向下下执行。
await命令后面是一个 Promise 对象。如果不是,会被转成一个立即resolve的 Promise 对象。
假如,我们需要请求一个api,拿到返回的数据,作为参数再去请求另一个api,拿到数据后在作为参数请求下一个,那么用then,该怎么写?依照上面的demo。

axios.get('http://localhost:3000/getData').then((value) => {
    return axios.get('http://localhost:3000/getData?name='+value.code);
}).then((res) => {
    return axios.get('http://localhost:3000/getData?name='+res.code);
}).then( (value) => {
    console.log(value)
}).catch(err => {});

node部分我们改成:

router.get('/getData', function(req, res, next) {
  var cxh = req.query.name;
  if(cxh && cxh == '100'){
        res.json({ "code": '200',"result":"get2 success!" });
  }else if(cxh && cxh == '200'){
        res.json({ "code": '300',"result":"finish!" });
  } else{
        res.json({ "code": '100',"result":"get success!" });
  }
});

运行结果

Paste_Image.png

要用n个then方法。
如果改称async函数呢?

class Axios {
    constructor(){}
    post(url){
        console.log(1)
        return this.getData(url,'POST')
    }
    get(url){
        console.log(2)
        return this.getData(url,'GET')
    }
    getData(url,methods){
        var promise = new Promise(function(resolve, reject){
            var client = new XMLHttpRequest();
            client.open(methods, url);
            client.onreadystatechange = handler;
            client.responseType = "json";
            client.setRequestHeader("Accept", "application/json");
            client.send();

            function handler() {
               if (this.readyState !== 4) {
                return;
               }
               if (this.status === 200) {
                  resolve(this.response);
               } else {
                  reject(new Error(this.statusText));
                }
            };
        });
        return promise;
    }
}

var axios = new Axios;
async function getData(){
    let res = await axios.get('http://localhost:3000/getData');
    let val = await axios.get('http://localhost:3000/getData?name=' + res.code);
    let cxh = await axios.get('http://localhost:3000/getData?name=' + val.code);
    console.log(res)
    console.log(val)
    console.log(cxh)
} 
getData();

结果:

Paste_Image.png

假如,上面三个await方法中有一个出现了reject,那么那么整个async函数都会中断执行。
如果代买如下:

var axios = new Axios;
async function getData(){
    let res = await axios.get('http://localhost:3000/getData');
    let val = await axios.get('http://localhost:3000/getData?name=' + res.code);
    let cxh = await axios.get('http://localhost:3000/getData?name=' + val.code);
    console.log(res)
    console.log(val)
    console.log(cxh)
    let fin =  await axios.post('http://localhost:3000/postData');
} 
getData();

假如上面三个方法中有一个出错,那么整个函数都会执行,也就是最后一个虽然和前面三个没关系,依然执行不了。那么怎么解决?

async function getData(){
    try{
        let res = await axios.get('http://localhost:3000/getData');
        let val = await axios.get('http://localhost:3000/getData?name=' + res.code);
        let cxh = await axios.get('http://localhost:3000/getData?name=' + val.code);
        console.log(res)
        console.log(val)
        console.log(cxh)
    }catch(err){
        
    }
    
    let fin =  await axios.post('http://localhost:3000/postData');
} 

这样就ok了。
2017年8月13日

上一篇下一篇

猜你喜欢

热点阅读