首页 > 解决方案 > 在 Node.js 中返回一个 Promise

问题描述

我无法解决这个问题。

取以下三个函数 wherea调用bb调用c

const c = () => {
    return new Promise( (resolve, reject) => {
        setTimeout(() => {
            resolve(new Date());
        }, "1750");
    });
};

const b = async () => {
    const result = await c();
    console.log("b(): %s", result);
    return result;
};

const a = async () => {
    const result = await b();
    console.log("a(): %s",result);
    return result;
};

console.log("Starting...");
const final_result = a();
console.log("Final Result: %s", final_result);
console.log("Ending...");

我希望b()等待/获取由 . 返回的承诺的结果c(),并将值传递给a(). 然而,看起来 promise 被一路向上传递到调用堆栈。

在此处输入图像描述

为了获得我想要的行为,我必须处理每个函数中的承诺:

const c = () => {
    return new Promise( (resolve, reject) => {
        setTimeout(() => {
            resolve(new Date());
        }, "1750");
    });
};

const b = async () => {
    const result = await c();
    console.log("b(): %s", result);
    return result;
};

const a = async () => {
    const result = await b();
    console.log("a(): %s",result);
    return result;
};
(async () => {
    console.log("Starting...");
    const final_result = await a();
    console.log("Final Result: %s", final_result);
    console.log("Ending...");
})()

在此处输入图像描述

为什么我不能只在一个函数中得到承诺的结果并返回呢?而且,如果我能做到,怎么做?

标签: node.jses6-promise

解决方案


推荐阅读