相关疑难解决方法(0)

节点JS Promise.all和forEach

我有一个类似于数组的数组,它暴露了异步方法.async方法调用返回数组结构,进而显示更多异步方法.我正在创建另一个JSON对象来存储从此结构获取的值,因此我需要小心跟踪回调中的引用.

我编写了一个强力解决方案,但我想学习一个更惯用或更干净的解决方案.

  1. 对于n级嵌套,该模式应该是可重复的.
  2. 我需要使用promise.all或类似的技术来确定何时解决封闭的例程.
  3. 并非每个元素都必然涉及进行异步调用.所以在嵌套的promise.all中我不能简单地根据索引对我的JSON数组元素进行赋值.尽管如此,我确实需要在嵌套的forEach中使用promise.all之类的东西,以确保在解析封闭例程之前已经完成了所有属性赋值.
  4. 我正在使用bluebird promise lib,但这不是必需的

这是一些部分代码 -

var jsonItems = [];

items.forEach(function(item){

  var jsonItem = {};
  jsonItem.name = item.name;
  item.getThings().then(function(things){
  // or Promise.all(allItemGetThingCalls, function(things){

    things.forEach(function(thing, index){

      jsonItems[index].thingName = thing.name;
      if(thing.type === 'file'){

        thing.getFile().then(function(file){ //or promise.all?

          jsonItems[index].filesize = file.getSize();
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous node.js promise

105
推荐指数
2
解决办法
18万
查看次数

标签 统计

asynchronous ×1

javascript ×1

node.js ×1

promise ×1