【问题标题】:How to return from nested function in Node.js?如何从 Node.js 中的嵌套函数返回?
【发布时间】:2020-02-22 10:53:52
【问题描述】:

我将我的 dynamoDB 函数包装到另一个函数中,但在将其返回给“item”常量时遇到了问题。我在这里缺少什么?

作品:

    const params = {
      TableName: table,
      Key: {
        id: id
      },
    };

    dynamoDb.get(params, (error, result) => {
      if (error) {
        console.error(error);
        callback(null, {
          statusCode: error.statusCode || 501,
          body: 'Couldn\'t fetch the item.',
        });
        return;
      }

      const item = result.Item
    })

不起作用(返回未定义):

  const getFromDb = () => {
    const params = {
      TableName: table,
      Key: {
        id: id
      },
    };

    dynamoDb.get(params, (error, result) => {
      if (error) {
        console.error(error);
        callback(null, {
          statusCode: error.statusCode || 501,
          body: 'Couldn\'t fetch the item.',
        });
        return;
      }

      return result.Item
    })
  }

  // Get from db
  const item = getFromDb()
  // do stuff with result item...

【问题讨论】:

标签: node.js asynchronous aws-lambda amazon-dynamodb


【解决方案1】:

您的代码中当前发生的情况是getFromDb 函数将运行dynamoDb.get(...) 并立即返回(在您的情况下未定义,因为getFromDb 中没有返回语句)。到getFromDb 返回时,您的 dynamoDb 请求甚至还没有解决,它会在未来某个时间解决并调用您提供的回调(error, result) => { ... }

要实现您所描述的,您需要:

  1. make getFromDb return Promise 只有在您的请求解决后才会解决
  2. await 调用该函数时,获取 Promise 解析的结果(或者如果它拒绝则错误)

.

// marking this function async is not required but good to have
// to not forget that this function returns a promise, not immediate result
const getFromDb = async () => {
  // wrapped body in a promise
  return new Promise((resolve, reject) => {
    const params = {
      TableName: table,
      Key: {
        id: id
      },
    }

    dynamoDb.get(params, (error, result) => {
      if (error) {
        // in case of error, we reject promise with that error
        reject(error)
        return
      }
      // otherwise, we resolve with result
      resolve(result.Item)
    })
  })
}

// usage with async/await
// I wrapped significant code in asynchronous function f and then called it
// just to emphasize that you can only use async/await inside async function
// if you are already in async function, you don't need to do this
const f = async () => {
  try {
    const item = await getFromDb();
    console.log(item)
  } catch(error) {
    // the error we rejected with
    console.error(error)
  }
}

f()


// alternative way without async/await, using Promise chaining
getFromDb()
  .then(item => console.log(item))
  .catch(error => console.error(error))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多