[英]How to pass variables through promise chain
我需要通过promise .then
链传递一个变量。 我找不到办法解决问题。 我对此很陌生,所以请耐心等待!
return foo.bar(baz)
.then((firstResult) => {
let message = firstResult;
})
.then(() => foo.bar(qux)
.then((secondResult) => {
message =+ secondResult;
console.log(message);
})
)
这样做的正确方法是什么?
不要使用承诺链。
你正在对foo.bar()
进行两次独立调用, 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);
});
只需将一个链转换为另一个链的回调:
return foo.bar(baz).then((firstResult) => {
let message = firstResult;
return foo.bar(qux).then((secondResult) => {
message =+ secondResult;
console.log(message);
return message;
});
});
我会解释为什么你的代码不起作用。
'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/
只有在foo.bar(baz)
完成后才需要调用foo.bar(qux)
。
这是你在另一个内部调用异步函数的方法:
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 );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.