javascript - 如何访问由 promise 内部的 promise 返回的值
问题描述
是否可以在 promise 之外访问 result2 的值。如果是,我该怎么做
例子
someFile1.someFunction1(req).then((result1)=>{
.
.
.
.
someFile2.someFunction2(req).then((result2)={
return(result2);
});
return(result1+result2);
})
解决方案
注意:我假设它们嵌套是有原因的。否则,请使用Promise.all
并行运行它们并在解析时添加您收到的数组。
如果我假设您的代码确实很大程度上如图所示,.
s 不会引入太多复杂性,那么有几种方法,但该示例中最简单的方法可能是嵌套 promise 处理程序:
someFile1.someFunction1(req)
.then((result1) => {
return someFile2.someFunction2(req)
.then((result2) => {
return result1 + result2;
});
})
.then(combined => {
// Use the combined result
});
或使用简洁的箭头功能:
someFile1.someFunction1(req)
.then(result1 =>
someFile2.someFunction2(req).then(result2 => result1 + result2)
)
.then(combined => {
// Use the combined result
});
或者当然,使用一个async
函数和await
:
const result1 = await someFile1.someFunction1(req);
const result2 = await someFile2.someFunction2(req);
const combined = result1 + result2;
甚至
const combined = (await someFile1.someFunction1(req)) + (await someFile2.someFunction2(req));
推荐阅读
- excel - 模拟旧 API 版本进行测试
- apache-kafka - Apache Kafka and Apache Storm Integration
- image - 如何通过http下载图像并在加载后将其显示给用户?
- docker - How to setup GitLab CE CI to user docker images for runners
- ios - Using AWS sdk on IOS without using Identity Pool
- reactjs - 从 react-ace 编辑器中的排水沟中删除所有注释
- android - 使用 Android 作为客户端和节点 js 作为服务器的 Google Auth
- groovy - Cassandra 在 Jmeter 错误中进行常规测试
- javascript - 通过具有多个键的另一个对象数组过滤对象数组
- java - Appium find element by 2 parameters in Java