使用 `then` 返回承诺值

Returning promise values with `then`

在下面的代码片段中,我使用 then 来获取承诺的结果。但是,不会返回 response。返回的是Promise { <pending> }.

我已经记录 response 并且可以看到它正确地返回了数据,而不是待定的承诺。那么为什么它要返回一个未决的承诺呢?我什至在对 describeTable 的调用中添加了一个 then 调用,但它仍然未决。

我已经阅读了以下问题,但它们没有帮助,所以请不要将它们标记为重复:

How do I return the response from an asynchronous call?

async/await implicitly returns promise?

const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-west-2'});
const docClient = new AWS.DynamoDB;

async function describeTable() {
    const params = {
        TableName: 'weatherstation_test',
    };

    let response;
    try {
        response = await docClient.describeTable(params).promise().then(result => result);
        console.log(response); // Logs the response data
    } catch (e) {
        console.error(e)
        throw e;
    }
    return response;
}

console.log(describeTable().then(result => result)); // Logs Promise { <pending> }

更新

所以我删除了第一个 then(在 promise() 之后),因为它是多余的。 @libik 的回答对我有用。 then 是 运行 的上下文,我不明白。

您无法从同步内容访问异步内容。

如果你想记录它,你必须像这样从里面做

describeTable().then(result => console.log(result))

在您的情况下,您正在记录异步函数的输出,这始终是一个承诺。


真正发生的事情:在Node.js中,所有同步内容首先执行,任何异步内容被放入事件循环,稍后执行。

所以首先执行这个

const AWS = require('aws-sdk');
AWS.config.update({region: 'eu-west-2'});
const docClient = new AWS.DynamoDB;
console.log(describeTable()

函数被调用,然后进入函数内部。因为是异步函数,所以会同步执行到第一个await.

const params = {
        TableName: 'weatherstation_test',
    };

    let response;
    try {
        response = await docClient.describeTable(params).promise()

现在这个 promise 被添加到 Event Loop 稍后执行,函数 describeTable() returns 到同步上下文(控制台日志)promise,它将通过你的所有函数链接稍后异步并记录此承诺(确实未决)。

现在您的同步上下文结束了。在上述承诺得到解决之前,您的应用程序可以同时执行其他部分(始终相同,从事件循环中获取事件,执行完全同步部分 - 这可以将另一个事件推送到事件循环,然后获取另一个事件并重复)

为了记录结果,您需要编写以下内容:

describeTable().then(result => console.log(result));