简体   繁体   English

如何从javascript异步函数访问返回值

[英]How to access a return value from a javascript async function

I have a Node.js function to fetch some value from DB table 我有一个Node.js函数可以从数据库表中获取一些值

var GetPoints = function(ibmdb, dbConnection, msisdn) {
    ibmdb.open(dbConnection, function(err, conn) {
        if (err) {
            //Error
        } else {
            conn.query('SELECT id,msisdn,points FROM t_points WHERE msisdn =' + msisdn, function(err, data) {
                console.log(err);
                if (!err) {
                    conn.close(function(err) {
                        if (!err) {}
                    });
                    consele.log(data);
                    //return data[0].POINTS;
                } else {
                    //Error
                }
            });
        }
        console.log("points" + points);
    });
}

I want to know how I can access the data object when I call this function from outside 我想知道从外部调用此函数时如何访问data对象

 var data = GetPoints(ibmdb, dbConnection, msisdn);

The value is coming correctly when I do a console.log 当我执行console.log时,该值正确显示

You can't return the value from an async function directly. 您不能直接从异步函数返回值。 Promises are generally used this situation. 通常会在这种情况下使用承诺。 You return a promise which can later be called .then upon to retrieve the said value. 您返回一个promise,以后可以将其称为.then来检索所述值。

var Promise = require('bluebird');
var GetPoints = function(ibmdb, dbConnection, msisdn) {
    // return a Promise
    return new Promise(function(resolve){
        ibmdb.open(dbConnection, function(err, conn) {
            if(err) throw err; // throw the error for it to be caught
            …
            conn.query('SELECT …', function(err, data) {
                if(err) throw err;
                …
                consele.log(data);
                //return data[0].POINTS;
                resolve(data);
}); }); }); }

GetPoints().then(function(data){
    // do something with data
}).catch(function(err){
    // handle err
});

Additionally, Bluebird has a promisify function that turns an async function (that takes a callback) into a function that returns a Promise. 此外,Bluebird具有一个promisify函数,它将一个异步函数(需要一个回调)变成一个返回Promise的函数。 It makes the above code much simpler: 它使上面的代码更加简单:

Note: Although I was reluctant because if you're using MySQL with which the promisification could be a little tricky: 1 , 2 . 注意:虽然我不愿意,因为如果你使用MySQL与该promisification可能是一个有点棘手: 12 But For now I've added .promisifyAll where it might seem redundant as it will likely be executed more than once, but hopefully bluebird's promisification is smart enough to handle this. 但是,到目前为止,我在.promisifyAll处添加了它,因为它可能会执行.promisifyAll ,因此看起来似乎是多余的,但希望bluebird的promisification足够聪明来处理此问题。 Nonetheless if you manage to promisify more efficiently you can just remove the redundant promisifyAll and just use X.yyyAsync methods as described: 但是,如果您设法更有效地进行承诺,则可以删除冗余的promisifyAll并仅使用X.yyyAsync方法,如下所述:

function GetConnection(ibmdb, dbConnection, msisdn){
    Promise.promisifyAll(ibmdb);
    return ibmdb.openAsync();
}

function getData(conn){
    Promise.promisifyAll(conn);
    return conn.queryAsync('SELECT …');
}

GetConnection()
.then(getData)
.then(function(data){
    // do something with data        
})

The callback function you gave after the SQL query gets executed asynchronously. 您在SQL查询异步执行后提供的回调函数。 Instead of trying to get that data outside the function, you should try to perform whatever you need to do inside. 与其尝试在函数之外获取数据,不如尝试在内部执行任何操作。 Keep in mind you can create another function and call it with the data to continue your work. 请记住,您可以创建另一个函数,并将其与数据一起调用以继续工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM