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

对于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很类似。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值