【问题标题】:How to Return Nested Promise如何返回嵌套的 Promise
【发布时间】:2018-01-03 18:38:29
【问题描述】:

我正在尝试从 getColumn 函数返回 result 参数。记录时,它返回未定义。

connection函数连接到一个SQL DB,查询返回一个数据集。

如何将变量传递回承诺链?

getColumn = function(columnName, table) {
  sql.connect(config.properties)
    .then(result => {
      let request = new sql.Request();
      request.query("SELECT " + columnName + " FROM " + table)
      .then(result => {
          // want to return this result from the getColumn function
          return result
      }).catch(err => {
          // Query error checks
      })
    }).catch(err => {
      // Connection error checks
    })
} // 

console.log(getColumn('username', 'Login'))

【问题讨论】:

  • 你试过在sql.connect()request.query()前面加一个return吗?这可能只是工作。 getColumn() 会返回一个 Promise,所以你需要另一个 then
  • 然后解决该承诺并获得结果,否则您可能需要使用回调
  • 好的,然后执行getColumn('username', 'Login').then((result) => console.log(result));之类的操作。

标签: javascript promise


【解决方案1】:

首先,您不能直接从getColumn() 返回值。该函数的内部是异步的,因此直到getColumn() 返回之后才会知道该值。您当前从getColumn() 获得undefined,因为它没有返回值。您所拥有的return 是异步.then() 处理程序,而不是getColumn()。无法从getColumn() 返回最终值。它是异步的。您必须返回一个承诺或使用回调。由于您已经在函数内部使用了 Promise,因此您应该只返回一个 Promise。

您可以从getColumn() 返回一个promise,并使用.then()await 与该promise 获取值。

要返回一个promise,你需要返回内部promise:

const getColumn = function(columnName, table) {
  // return promise
  return sql.connect(config.properties).then(result => {
    let request = new sql.Request();
    // chain this promise onto prior promise
    return request.query("SELECT " + columnName + " FROM " + table);
  });
} // 

getColumn('username', 'Login').then(val => {
   console.log(val);
}).catch(err => {
   console.log(err);
});

【讨论】:

  • 好的。由于它是异步的,我将无法将结果传递给另一个函数并遍历数组吗?我正在尝试制作一个实用函数,可以用作更新列值的中介。
  • @Matthew - 你永远不会直接从函数返回异步结果。只是不能在Javascript中做到这一点。你返回承诺。您可以使用await 循环调用返回proimse 的异步函数的数组。但是,我们无法真正帮助解决这部分问题,因为您没有显示任何代码。我想我已经回答了你最初问的问题。也许你应该接受这一点。在循环中使用await 进行研究,然后,如果遇到困难,请写一个关于如何在循环中使用getColumn() 的新问题。
猜你喜欢
  • 2019-01-09
  • 2013-10-26
  • 2014-02-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 2020-04-13
  • 2017-04-03
  • 1970-01-01
相关资源
最近更新 更多