使用Promises递归修改对象

时间:2016-06-18 17:28:28

标签: javascript node.js recursion promise

我正在尝试遍历ElasticSearch的结果,并通过替换数组中的项目来修改原始对象。我几乎完成了,但Promise不止一次得到解决,让我没有可用的结果。

我正在使用breaks <- as.numeric(formatC(0 + c(0, 0.2315, 10), digits = 3, width = 1L)) cut(x, breaks = breaks) ## [1] (0,0.232] ## Levels: (0,0.232] (0.232,10] 将原始数组替换为函数调用的结果,并且几乎。保持对象的原始结构和source.included = Array.map()数组中的顺序非常重要,这就是我决定尝试这种方法的原因。我试图将自己定位在this example上,但Promise.all()不知何故无法解决这些承诺。有什么想法吗?

included

1 个答案:

答案 0 :(得分:1)

避免使用Promise constructor antipattern

你不能(绝不)多次调用resolve - 在你的情况下,从map循环中调用。请改用:

function recursiveGet (source) {
  return client.mget({
    body: {
      docs: docsToFetch
    }
  }).then(response => {
    let promises = source.included.map(item => {
      return somethingAsync(response) // did you mean `item` here?
    })
    return Promise.all(promises);
  })
  .then(resolved => {
    let morePromises = resolved.map(doc => {
//                              ^^^ another loop...
      if (doc.included && !doc.resolved) {
        return recursiveGet(doc);
      } else {
        return doc;
      }
    });
    return Promise.all(morePromises).then(moreResults => {
//         ^^^^^^^^^^^ another Promise.all!
      source.included = moreResults;
      return source;
    });
  });
}

如果您不想要两个连续循环,您还可以直接将每个结果处理回调链接到somethingAsync承诺。

相关问题