栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Node JS Promise.all和forEach

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Node JS Promise.all和forEach

使用一些简单的规则非常简单:

  • 每当您在中创建承诺时
    then
    ,都将其返回
    -您不返回的任何承诺都不会在外面等待。
  • 每当您创建多个promise时,
    .all
    它们就会以
    这种方式等待所有promise,并且其中任何一个的错误都不会消失。
  • 每当您嵌套
    then
    s时,通常都可以在中间返回
    -
    then
    链通常最多为1层深。
  • 每当执行IO时,它都应该带有承诺 -应该在承诺中,或者应该使用承诺来表明其完成。

还有一些提示:

  • 映射
    .map
    比使用
    for/push
    - 更好地完成 -如果您要通过函数映射值,则
    map
    可以简洁地表达一个动作一一应用并汇总结果的概念。
  • 如果是免费的,并发比顺序执行要好 -并发执行并等待它们
    Promise.all
    比一个接一个地执行要好-每个等待都在下一个执行之前要好。

好的,让我们开始吧:

var items = [1, 2, 3, 4, 5];var fn = function asyncMultiplyBy2(v){ // sample async action    return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));};// map over forEach since it returnsvar actions = items.map(fn); // run the function over all items// we now have a promises array and we want to wait for itvar results = Promise.all(actions); // pass array of promisesresults.then(data => // or just .then(console.log)    console.log(data) // [2, 4, 6, 8, 10]);// we can nest this of course, as I said, `then` chains:var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(    data => Promise.all(data.map(fn))).then(function(data){    // the next `then` is executed after the promise has returned from the previous    // `then` fulfilled, in this case it's an aggregate promise because of     // the `.all`     return Promise.all(data.map(fn));}).then(function(data){    // just for good measure    return Promise.all(data.map(fn));});// now to get the results:res2.then(function(data){    console.log(data); // [16, 32, 48, 64, 80]});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380706.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号