【问题标题】:How to access a variable outside the .then scope in nodejs如何在nodejs中访问.then范围之外的变量
【发布时间】:2020-08-06 15:54:45
【问题描述】:

需要一些帮助。

所以,就像我有一个函数,我从那里返回一个 Promise(基于 q)。现在在第二个函数中,我通过使用 .then 链接该函数来调用该函数,现在在这个 .then 中,我编写了一个用于某些操作的方法,并基于该方法我期待一个值。在该返回值之后,在.then 之外,我的数据库连接代码开始了。所以现在的问题是我无法访问 .then 中的方法返回的变量值,因此我的数据库返回数据不正确。

在代码中是这样的。

getSomeWarehouseData(){
return defer.promise
}

getOracleData(){

   getSomeWarehouseData().then(function(returnedValue){
      ***some data manipulation

      function getCustomizedDetails(){
      return data;
      }

      custom_data = getCustomizedDetails()

})//.then scope ends

// Unable to access custom_data outside the .then 

**** console.log(custom_data)// undefined****

**Oracle Code getting Started****

oracledb.getConnection(
{
***connection settings
},
function(err, connection)
{

***inside here I need to access the custom_data variable*** which is not accessible currently.

})

}

【问题讨论】:

  • 你试过用箭头函数((err, connection) => {})代替function(err, connection)吗?
  • @MaxAmorim,在 .then 闭包之外无法访问该变量,因此即使将函数更改为箭头函数,它也不起作用。因此,如果您看到我在此处提供的代码示例,我无法直接从我编写的地方访问该变量**Oracle 代码入门****
  • 您没有显示在您声明 custom_data 的代码中。您应该在getSomeWarehouseData() 之外声明,在then() 语句内部进行操作,并在oracledb.getConnection() 上重新使用它
  • @MaxAmorim,感谢您的评论,我做了同样的事情,我已经在 getOracleData() 函数中声明它并在 .then 中使用它但是它在 .then 之外无法访问虽然它仍然在 getOracleData() 函数中。这意味着,在 .then({ }) 链之外无法访问该变量数据。
  • 您说“不可访问”是什么意思?是undefined?您没有将oracledb.getConnection 放在then 中的具体原因是什么?然后你会确保函数的数据。

标签: javascript node.js oracle promise node-oracledb


【解决方案1】:

使用 javascript 的异步术语的代码存在问题。使用getOracleData 中的第二个函数和then

getSomeWarehouseData() {
return defer.promise;};

getOracleData() {

getSomeWarehouseData().then(function (returnedValue) {
        // **
        // * some data manipulation

        function getCustomizedDetails() {
            return data;
        }

        custom_data = getCustomizedDetails();

        oracledb.getConnection({
            // **
            // * connection settings
        },
        function (err, connection) {

            // **
            // * inside here I need to access the custom_data variable ** * which is not accessible currently.
            console.log(custom_data);

        });

    }) ;//.then scope ends

    // Unable to access custom_data outside the .then 

    // **
    // ** console.log(custom_data) // undefined****

    // **
    // Oracle Code getting Started ** *};

【讨论】:

  • 这是我的第一种方法,但是,问题是数据库连接没有建立,因此可能 connection.execute 失败,尽管我没有检查。
  • 另外,当我尝试调用 getOracleData 以从中获取 sqlResponse 时,我在查询中绑定它的 custom_data 变量对我不可用,并且查询列将其返回为“未定义” ”。我只是通过在其结果上链接 .then 来调用 getOracleData
猜你喜欢
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多