您的位置:首页 > 大数据 > 人工智能

关于Promise,Generator,async / await 对异步的处理

2017-07-26 12:21 946 查看
对于js关于异步是它的一大特点,但有时候也成为了一大难点,金字塔的地狱式回调,现在来浅谈关于js的异步处理方案。

众所周知的promise

node 的高并发是新的特性,但是回调使其变得有点尴尬,在promise出来后好了很多先看栗子:

let foo=new Promise
foo()
.then((result) => console.log(result);)
.catch((reason) => console.error(reason););


在then里面可以对数据进行处理,还可以这样

let foo=new Promise
foo()
.then((result1) => console.log(result1);)
.then((result2) => console.log(result2);)
.then((result3) => console.log(result3);)
.then((result4) => console.log(result4);)
.
.
.
.catch((reason) => console.error(reason););
//成功的话 result1,result2,result3,result4


如果失败会在catch捕获到只要在前面的then里面执行失败就会直接跳到catch里面,失败之后的then()不会被执行,
```


let foo=new Promise

foo()

.then((result1) => console.log(result1);)

.then((result2) => console.log(result2);) //在这里失败了

.then((result3) => console.log(result3);)

.then((result4) => console.log(result4);)

.

.

.

.catch((reason) => console.error(reason););

//失败的话 result1,reason

不过Promise仍然存在缺陷,它只是减少了嵌套,并不能完全消除嵌套。举个例子,对于多个promise串行执行的情况,第一个promise的逻辑执行完之后,我们需要在它的then函数里面去执行第二个promise,这个时候会产生一层嵌套。另外,采用Promise的代码看起来依然是异步的。
下面谈谈Generator
在node的回调中我们常用的tj/co(github仓库有介绍),它就是用generator结合promise来实现的,废话不多说上代码,阿里的egg.js用的就是yield,不过官方建议用async / await


// yield后面是一个生成器 generator


const getData = function* () {

return new Promise((resolve, reject) => {

request(options, (err, res, body) => {

if (err) {

reject(err);

}

resolve(body);

});

});

};

co(function* () {

const result = yield getData;

// … 如果有多个异步流程,可以放在这里,比如多个一部都可以

// const r1 = yield getR;

.

.

.

// 每个yield相当于暂停,执行yield之后会等待它后面的generator返回值之后再执行后面其它的yield逻辑。

return result;

}).then(function (value) {

console.log(value);

}, function (err) {

console.error(err.stack);

});

可以看出跟Promise不同的是到现在就把js给掰弯了,现在他是同步的了。。。。

但是在es7里面async / await对异步的处理已经飞起来了,毕竟co解决异步只是个过渡方案。目前目前async / await 在主流浏览器已经支持了。。


async function asyncFun() {

try {

const value = await getData();

// … 和上面的yield类似,如果有多个异步流程,可以放在这里,比如

// const r1 = await getR1();

// 每个await相当于暂停,执行await之后会等待它后面的函数(不是generator)返回值之后再执行后面其它的await逻辑。

return value;

} catch (err) {

console.log(err);

}

}

“`

每个async里面的await 都要等到有返回值才会继续执行程序,这个跟yield很类似。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息