更多例子
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 的顺序执行和并行执行 http://zyy1217.com/2017/03/25/promise/
构建 Promise 队列实现异步函数顺序执行
补充
ES6 Promise 中断
中断或取消 Promise 链的可行方案
- (1)reject()
- (2)throw new Error()
一般来说, 不要在 then 方法里面定义 reject 状态的回调函数 (即 then 的第二个参数), 总是使用 catch 方法.
来源: http://www.jianshu.com/p/dbda3053da20