【问题标题】:Returning promise values with `then`使用 `then` 返回承诺值
【发布时间】:2019-10-21 09:26:04
【问题描述】:

在下面的代码 sn-p 中,我使用 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 的上下文。

【问题讨论】:

  • 如果你使用await就不需要then构造。
  • 尝试删除.then(...)

标签: node.js promise aws-sdk-nodejs


【解决方案1】:

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

如果你想记录它,你必须像这样从内部进行

describeTable().then(result =&gt; 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被添加到事件循环中,稍后执行,函数describeTable()返回到同步上下文(控制台日志)promise,稍后将通过你的所有函数异步链接,你记录这个promise(这确实是待定的)。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-03-09
      • 2018-03-10
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多