如何通过承诺链传递变量

时间:2018-07-05 12:37:07

标签: javascript variables promise

我需要通过promise .then链传递变量。我找不到解决办法。我对此很陌生,所以请多多包涵!

return foo.bar(baz).then((firstResult) => {
let message = firstResult;
})
.then(() => foo.bar(qux).then((secondResult) => {
message =+ secondResult;
console.log(message);
})
)

请问这样做的正确方法是什么?

4 个答案:

答案 0 :(得分:6)

请勿为此使用承诺链。

您正在对foo.bar()进行两个独立的调用,而这两个都不依赖于另一个的结果。

独立制作它们,并最终通过Promise.all获取所有数据。

var promises = [
    foo.bar(baz),
    foo.bar(qux)
];
Promise.all(promises).then( results => {
    let message = results[0] + results[1];
    console.log(message);
});

答案 1 :(得分:3)

只需将一个链链接到另一个链的回调中即可

 return foo.bar(baz).then((firstResult) => {
    let message = firstResult; 
    return foo.bar(qux).then((secondResult) => {
       message =+ secondResult;
       console.log(message);
       return message;
    });
});

答案 2 :(得分:1)

我将解释为什么您的代码不起作用。

“ let”变量的范围保留在您放置的括号之间。 因此,在下一个.then()中,该消息变量失去了作用域,您无法使用它。

在此处阅读文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

要解决您的问题,您可以在promise链外声明变量,并像下面这样写:

let message; // Declare it outside so that the variable is in scope throughout the promise chain

return foo
  .bar(baz)
  .then((firstResult) => {
    message = firstResult; // Set the value here
  })
  .then(() => foo
    .bar(qux)
    .then((secondResult) => {
      message += secondResult;
      console.log(message);
    }));

有关工作示例,请参阅以下内容:https://jsfiddle.net/sivcan/h3pguw4e/

答案 3 :(得分:0)

仅在foo.bar(qux)完成后才需要致电foo.bar(baz)

这是在另一个内部调用异步函数的方式:

return foo.bar(baz).then((firstResult) => {
    let message = firstResult;
    // do some operation with firstResult
    foo.bar(qux).then((secondResult) => {
      message =+ secondResult;
      console.log(message);
    });
});                       

更好的方法:您可以创建一个promise数组,然后使用Promise.all()使用它,如下所示:

var promises = [
    foo.bar(baz),
    foo.bar(qux)
];

Promise.all(promises.map(p => p.catch(error => null))).then( results => {
    let firstResult = results[0]
    let secondResult = results[1];
    console.log("firstResult -->", firstResult);
    console.log("secondResult -->", secondResult );
});                               
相关问题