与承诺混淆

时间:2018-07-12 07:50:08

标签: node.js

我正在编写一个节点js代码以从Azure SQL中获取数据。在这里,我可以正确获取并打印它。但是问题是我想在另一个位置打印它。下面是我的代码。

var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var tp = require('tedious-promises');

var x = [];
// Create connection to database
var config = {
    userName: 'myUserName',
    password: 'MyPwd',
    server: 'myServer',
    options: {
        database: 'myDB',
        encrypt: true
    }
}
tp.setConnectionConfig(config);

function queryDatabase() {
    console.log('Reading rows from the Table...');
    tp.sql("select TOP 10 title FROM dbo.Table").forEachRow(function(row) {
            x.push(row.title + "====");
        }).execute()
        .then(function(results) {
            console.log(x);   <======= It is printing here correctly.
        }).fail(function(err) {
            console.log(err);
        });
}

queryDatabase();
console.log("========");
console.log(x);<============ I want it to print the value here

我当前的输出如下。

========
[]
(node:15608) [DEP0064] DeprecationWarning: tls.createSecurePair() is deprecated. Please use tls.Socket instead.
[Here all the values are printed ]

但是我的预期输出是

(node:15608) [DEP0064] DeprecationWarning: tls.createSecurePair() is deprecated. Please use tls.Socket instead.
[Here all the values are printed ]
========
[Here all the values are printed ]

请让我知道我要去哪里错了,我该怎么办。

谢谢

1 个答案:

答案 0 :(得分:0)

Promise是异步的,您必须在函数中使用回调或将函数转换为promise:

回调版本:

function queryDatabase(callback) {
    var x = [];
    console.log('Reading rows from the Table...');
    tp.sql("select TOP 10 title FROM dbo.Table").forEachRow(function(row) {
            x.push(row.title + "====");
        }).execute()
        .then(function(results) {
            console.log(x);   <======= It is printing here correctly.
            return callback(null, x);
        }).fail(function(err) {
            console.log(err);
            return callback(err, null);
        });
}


queryDatabase(function(err, result){

    if(err){
        console.log(err);
    } else {
        console.log("========");
        console.log(x);<============ I want it to print the value here
    }

});

承诺版本:

function queryDatabase() {

    return new Promise(function(resolve, reject){
        var x = [];
        console.log('Reading rows from the Table...');
        tp.sql("select TOP 10 title FROM dbo.Table").forEachRow(function(row) {
            x.push(row.title + "====");
        }).execute()
        .then(function(results) {
            console.log(x);   <======= It is printing here correctly.
            return resolve(x);
        }).fail(function(err) {
            console.log(err);
            return reject(err);
        });
    });
}


queryDatabase()
.then(function(result){

      console.log("========");
     console.log(result);<============ I want it to print the value here
})
.catch(function(err){

   console.log(err) 

});