es6 队列_ES6 Promise 并行执行和顺序执行

更多例子

1.Promise.all 并行执行promise

getA和getB并行执行,然后输出结果。如果有一个错误,就抛出错误

/** * 每一个promise都必须返回resolve结果才正确 * 每一个promise都不处理错误 */ const getA = new Promise((resolve, reject) => { //模拟异步任务 setTimeout(function(){ resolve(2); }, 1000) }) .then(result => result) const getB = new Promise((resolve, reject) => { setTimeout(function(){ // resolve(3); reject('Error in getB'); }, 1000) }) .then(result => result) Promise.all([getA, getB]).then(data=>{ console.log(data) }) .catch(e => console.log(e));

getA和getB并行执行,然后输出结果。总是返回resolve结果

/** * 每一个promise自己处理错误 */ const getA = new Promise((resolve, reject) => { //模拟异步任务 setTimeout(function(){ resolve(2); }, 1000) }) .then(result => result) .catch(e=>{ }) const getB = new Promise((resolve, reject) => { setTimeout(function(){ // resolve(3); reject('Error in getB'); }, 1000) }) .then(result => result) .catch(e=>e) Promise.all([getA, getB]).then(data=>{ console.log(data) }) .catch(e => console.log(e));

2.顺序执行promise

先getA然后getB执行,最后addAB

2.1 方法一——连续使用then链式操作

function getA(){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(2); }, 1000); }); } function getB(){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(3); }, 1000); }); } function addAB(a,b){ return a+b } function getResult(){ var obj={}; Promise.resolve().then(function(){ return getA() }) .then(function(a){ obj.a=a; }) .then(function(){ return getB() }) .then(function(b){ obj.b=b; return obj; }) .then(function(obj){ return addAB(obj['a'],obj['b']) }) .then(data=>{ console.log(data) }) .catch(e => console.log(e)); } getResult();

2.2 方法二——使用promise构建队列

function getResult(){ var res=[]; // 构建队列 function queue(arr) { var sequence = Promise.resolve(); arr.forEach(function (item) { sequence = sequence.then(item).then(data=>{ res.push(data); return res }) }) return sequence } // 执行队列 queue([getA,getB]).then(data=>{ return addAB(data[0],data[1]) }) .then(data => { console.log(data) }) .catch(e => console.log(e)); } getResult();

2.3方法三——使用async、await实现类似同步编程

function getResult(){ async function queue(arr) { let res = [] for (let fn of arr) { var data= await fn(); res.push(data); } return await res } queue([getA,getB]) .then(data => { return addAB(data[0],data[1]) }).then(data=>console.log(data)) }

3. 总结

实现异步队列函数的三种方式

方法一——连续使用then链式操作

方法二——使用promise构建队列

方法三——使用async、await实现类似同步编程,async函数内部实现同步

参考

Promise的顺序执行和并行执行

构建Promise队列实现异步函数顺序执行

补充

ES6 Promise中断

中断或取消Promise链的可行方案

(1)reject()

(2)throw new Error()

一般来说,不要在then方法里面定义 reject 状态的回调函数(即then的第二个参数),总是使用catch方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值