首页 > 解决方案 > 如何访问由 promise 内部的 promise 返回的值

问题描述

是否可以在 promise 之外访问 result2 的值。如果是,我该怎么做

例子

someFile1.someFunction1(req).then((result1)=>{
.
.
.
.

    someFile2.someFunction2(req).then((result2)={
        return(result2);
    });

    return(result1+result2);

})

标签: javascriptnode.js

解决方案


注意:我假设它们嵌套是有原因的。否则,请使用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));

推荐阅读