如何返回嵌套的 Promise [英] How to Return Nested Promise

查看:83
本文介绍了如何返回嵌套的 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to return the result parameter from the getColumn function. When logging, it returns undefined.

连接函数连接到一个 SQL 数据库,查询返回一个数据集.

The connection function connects to a SQL DB and the query returns a data set.

如何将变量传回承诺链?

How can I pass the variable back up the promise chain?

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'))

推荐答案

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

First off, you can't return a value directly form getColumn(). The insides of that function are asynchronous so the value won't be known until AFTER getColumn() returns. You are currently getting undefined from getColumn() because it has no return value. The return you do have is to an asynchronous .then() handler, not for getColumn(). There is no way to return the final value from getColumn(). It's asynchronous. You have to either return a promise or use a callback. Since you're already using promises internal to the function, you should just return a promise.

您可以从 getColumn() 返回一个承诺,并使用带有该承诺的 .then()await 来获取值.

You can return a promise from getColumn() and use .then() or await with that promise to get the value.

要返回承诺,您需要返回内部承诺:

To return a promise, you need to return the internal promises:

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);
});

这篇关于如何返回嵌套的 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆