Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

promise 顺序调用 #5

Open
sunhengzhe opened this issue Jul 27, 2017 · 4 comments
Open

promise 顺序调用 #5

sunhengzhe opened this issue Jul 27, 2017 · 4 comments

Comments

@sunhengzhe
Copy link
Member

sunhengzhe commented Jul 27, 2017

今天写代码碰到一个场景,有多个异步任务,且异步任务需要顺序执行(执行完一个之后执行下一个)。
最后异步任务写成 promise 之后都放在了一个数组里,需求是让数组里的 promise 顺序处理。代码如下

var arr = [
    () => new Promise(resolve => setTimeout(() => {
        console.log('p1 done');
        resolve();
    }, 3000)),
    () => new Promise(resolve => setTimeout(() => {
        console.log('p2 done');
        resolve();
    }, 2000)),
    () => new Promise(resolve => setTimeout(() => {
        console.log('p3 done');
        resolve();
    }, 1000)),
];

怎么实现,让这个数组里的 promise 顺序执行?即打印出 ->->-> p1 done ->-> p2 done -> p3 done

@sunhengzhe
Copy link
Member Author

使用 reduce ~

arr.reduce((prev, cur) => {
    var p = prev().then(() => cur());
    return () => p;
});

@keer3
Copy link
Member

keer3 commented Jul 27, 2017

arr.reduce((prev, cur) => {
    return prev.then(cur);
}, Promise.resolve()).then();

@sunhengzhe
Copy link
Member Author

@miSunLaughing 用 async/await 也太狡猾了,哈哈

@miSunLaughing
Copy link

miSunLaughing commented Jul 27, 2017

@sunhengzhe 哈哈,我把格式调下把代码贴出来吧

// 使用async函数
async function chainAsync(arr) {
  var ret = null;
  try {
    for(var item of arr) {
      ret = await item();
    }
  } catch(e) {
    /* 忽略错误,继续执行 */
  }
  return ret;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants