为什么我可以等待此代码但不能使用 .then?

Why can I await this code but not use .then?

Node.JS 10.15,无服务器,lambda,本地调用

示例 A) 这有效:

export async function main(event) {
    const marketName = marketIdToNameMap[event.marketId];
    const marketObject = marketDirectory[marketName];
    const marketClient = await marketObject.fetchClient();

    const marketTime = await marketObject.getTime(marketClient);
    console.log(marketTime);
}

示例 B) 并且有效:

export function main(event) {
    const marketName = marketIdToNameMap[event.marketId];
    const marketObject = marketDirectory[marketName];

    marketObject.fetchClient().then((marketClient)=>{
        marketObject.getTime(marketClient).then((result) => {
            console.log('<---------------> marker 1 <--------------->');
            console.log(result);
        });
    });
}

示例 C) 但这不是:

export async function main(event) {
    const marketName = marketIdToNameMap[event.marketId];
    const marketObject = marketDirectory[marketName];
    const marketClient = await marketObject.fetchClient();

    console.log('<---------------> marker 1 <--------------->');

    marketObject.getTime(marketClient).then((result) => {
        console.log('<---------------> marker 22 <--------------->');
        console.log(result);
    });
}

getTime 的内容适用于所有示例:

function getTime(marketClient){
    return new Promise((resolve, reject) => {
        return marketClient.getTime((err, result) => {
            if (err) {
                reject(err);
            }
            resolve(result);
        });
    }).catch(err => {
        throw err;
    });
}

显然,将 async/awaits 与经典的 promise then-ables 混合使用似乎是个问题。我会 期望 SAMPLE C 工作,因为 getTime() 正在返回一个承诺。然而,代码只是静静地结束,从不击中第二个标记。我必须把第一个标记放在那里只是为了确保任何代码都是 运行。感觉我应该可以混合 async/await 和 thenables,但我不能在这里考虑一些东西。

@adrian,不

您既不等待也不 returning 来自 marketObject.getTime().then() 的承诺,这将导致该承诺链独立执行,主函数 returning 和进程关闭.请记住.. then return 也是一个承诺。

解决方案是

await marketObject.getTime(marketClient).then(...

return marketObject.getTime(marketClient).then(...

无论哪种方式,都可以将承诺链接到主要功能,这样无论执行什么,它都会始终等待所有承诺解决(或拒绝)。

我怀疑示例 B 可以工作,因为 main 不是异步的,Lambda 将等待 event-loop 完成。即即使 main returned 早,它也会执行承诺链。

https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

If you don't use callback in your code, AWS Lambda will call it implicitly and the return value is null. When the callback is called, AWS Lambda continues the Lambda function invocation until the event loop is empty.

... 我怀疑如果你 return 一个 Promise(就像你在示例 C 中所做的那样),那么 Lambda 将在它解决后立即终止进程,这是因为你没有 await/return .then() 链,因此您创建的浮动承诺链将不会执行。