async/await完美解决异步队列 / 网络研习社#46

in cn •  5 years ago 

async.jpg

在JavaScript中几乎所有的函数都是异步的,这有好处,但也引起了一些问题。比如,如何保证异步函数按顺序执行呢?

举个例子,有三个任务:A, B , C ,因为是异步函数,所以JS几乎会同时调用这三个函数,谁先执行完,谁后执行完并不知道。如果是不相关的三件事倒还好,如果你需要它们顺序执行的话,那可要费点劲了。

前面我提到Promise的解决方案,A -> B -> C ,它有专门的 .then的用法,有点类似这样:

Promise{
(A is done)
}
.then(B is done)
.then(C is done)



这种用法还不错,但还有一种更好的方案,那就是async/await异步队列!用它写的话是这样的:

async{
  await (A is done)
  await (B is done)
  await (C is done)
}



这种写法更符合人的思维逻辑,更容易理解。async函数还比较新,webpack打下包也能用的。用它来写队列真是一个完美的方案。

多个异步任务用async/await来解决是个完美的方案,前提是这些异步任务都要用Promise包装一下,要有一个明确的结束点,否则谁也没法知道结束的时间点。

promise.jpg

完成了promise函数的封装,把它们丢进async函数中就行啰。

async function main(){
   await A任务
   await B任务
   await C任务
}
main()
//A,B,C 都是Promise函数,它们将按顺序执行


async函数和普通函数写法差不多,没有太大的差异,但它却能解决异步的问题,是个相当完美的方案!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

s试试一下

699

788

999

22222

  ·  5 years ago 

!thumbup
恭喜你!您的这篇文章入选 @justyy 今日 (2019-10-31) 榜单 【优秀的文章】, 回复本条评论24小时内领赏,点赞本评论将支持 @dailychina 并增加将来您的奖赏。
@justyy 是CN区的见证人,请支持他,给他投票,或者设置justyy为见证人代理。感谢!@justyy的主要贡献:https://steemyy.com

Congratulations! This post has been selected by @justyy as today's (2019-10-31) 【Good Posts】, Steem On! Reply to this message in 24 hours to get rewards. Upvote this comment to support the @dailychina and increase your future rewards! ^_^

SteemIt 工具、API接口、机器人和教程
SteemIt Tools, Bots, APIs and Tutorial



If you believe what I am doing, please consider a spare vote voting me here, thank you very much indeed.

@justyy - the author of https://SteemYY.com and I have been a Steem Witness for more than a year now.

@tipu curate

Upvoted 👌 (Mana: 5/15)