【问题标题】:How to pass then() return object as input to then() function using NodeJS Map function如何使用NodeJS Map函数将then()返回对象作为输入传递给then()函数
【发布时间】:2017-02-23 15:29:18
【问题描述】:

我是使用 NodeJS 的新手,我能够从本地文件系统中提取 JSON 文件,使用 MAP 函数我们必须按顺序执行 2 个函数。对于第一个函数的结果,应使用 .then() 为第二个函数输入结果。

您能帮我提供示例代码吗?

【问题讨论】:

标签: javascript node.js promise


【解决方案1】:

我不确定我是否理解你的意思,但链接多个承诺的工作方式如下:

computeResultOneAsyncronously()
    .then(function(resultOne) {
        return computeResultTwoAsynchronously(resultOne);
    }).then(function (resultTwo) {
        return computeResultThreeAsynchronously(resultTwo);
    }).then(function (resultThree) { 
      // and so on */
    };

使用.map() 对数组元素连续应用两个函数的工作方式如下:

var arr = [1,2,3,4];
function f1(x) { return x + 1 }
function f2(x) { return x * 2 }
var result = arr.map(f1).map(f2);
// yields [4, 6, 8, 10]

我希望这有助于解决您的问题。

【讨论】:

  • 但您的答案中没有 map!你是女巫吗? :p
  • 你是对的。我不明白map 应该适用于什么,因为这个问题还不是很清楚。但是,我将添加一个示例。
  • 我在开玩笑:p
猜你喜欢
  • 2014-07-13
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 2017-07-16
  • 2018-02-15
  • 2019-04-13
  • 1970-01-01
  • 2020-07-31
相关资源
最近更新 更多