Javascript promise 结果范围

标签 javascript promise

<分区>

我需要链接一些异步操作。我正在尝试编写使用 express 的 Parse.com 云代码。 (我认为 express 是 promise 支持的来源)。我明白为什么 promise 很有值(value),但我仍然不确定有几件事。首先是如何收集顺序操作的结果。下面的代码说明:

function doAsnychThingsInSequence(params) {
  return doThing0(params).then(function(resultOfThing0) {
    // thing1 depends on resultOfThing0
    doThing1(resultOfThing0);
  }).then(function(resultOfThing1) {
    // here is where I am confused.
    // thing2 depends on the results of thing0 and thing1
    doThing2(resultOfThing0 /* out of scope?? */, resultOfThing1);
  }, function(error) {
    // handle error
  });
}

thing1 完成后,我需要两个操作的结果。我想我可以在函数顶部分配一个变量并将其分配给第一个回调中的第一个结果,这是正确的方法吗?我想,我困惑的核心是问题二......

  return doThing0(params0).then(function(resultOfThing0) {
    doThing1(resultOfThing0);
    // what does return mean here?  does what I return here relate to the
    // parameters of the next function?
    return "foo";
  }).then(function(param) {
    // what is in param?  is it "foo"?
  }, function(error) {
});

最佳答案

Promises 可以被想象成一个流处理:一个函数获取输入,用它做一些事情并将它传递给链中的下一个函数。

因此,如果您需要进一步传递输入(对于链)参数,您应该将它们包含在 输出数据,以便链中的下一个可以使用它们:

function doThing1(params1) {
  ...
  return [params1, result1];
}

function doThing2(params1, params2) {
  ...
}

正如您所提到的,您可以在 doThing1 和 doThing2 之外使用一些变量,但这会使这些函数处于全状态,这可能会导致各种副作用。通常不需要异步处理。

关于Javascript promise 结果范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21662899/

相关文章:

javascript - 将 Function.prototype.bind 与参数数组一起使用?

javascript - 如何为每组词突出显示一个词?

javascript - 结果按第一个 ajax 的顺序排列,但在 for 循环内部顺序随机改变。为什么?

javascript - 为什么我的对象 contentDocument 返回 null?

javascript - 如何在 chrome 扩展中使用 AJAX 向 ‘My XAMPP server’ 发送 GET 请求

javascript - 解析云代码 - promise 问题

javascript - JQuery 取了错误的值

node.js - Jest 模拟一个 toPromise 函数 - got .toPromise 不是一个函数

Javascript promise 停留在挂起状态

javascript - 在 promise 在其他代码位置解析后运行代码