简体   繁体   English

如何在 javascript 中使用 defer/promise 进行数据库调用

[英]how to use defer/promise in javascript for a db call

I am having db.js with db related functions, I want to make call to db.js and wait until it returns the query result.我有带有 db 相关函数的 db.js,我想调用 db.js 并等待它返回查询结果。 But the result is returned after the execution of the db call.但是执行db调用后返回结果。 Can anyone please help how to solve this.任何人都可以请帮助如何解决这个问题。

Code sample:代码示例:

var Q = require('q');

db= require("./dbaccess.js");

function waitfor(ms){

     var deferred = Q.defer();

     setTimeout(function() {

        deferred.resolve(db);
     }, 5000);
     return deferred.promise;
}

waitfor(2000).done(function(dbcall) {

console.log('contrived example '+ dbcall.query1()); 

});

dbacess.js:数据库访问.js:

var sql = require('mssql');

var config = {

user: 'xx',

    password: 'xxx',

    server: 'aaa', 

    database: 'RequestCenter',

    stream: true,  

}

this.query1=function() {

sql.connect(config, function(err) {

    var result;
    var request = new sql.Request();
    request.query("select * from dbo.AcAccount where Name like 'AutomationCli%' ");  
    request.on('row', function(row) {
        console.log(row.Name);
        result = row.Name;
    });

    request.on('error', function(err) {
        console.log("err : "+err); 
    });

    request.on('done', function(returnValue) {
        console.log("done"); 
    });
    return result;
});



sql.on('error', function(err) {

console.log("sql err : "+err);

});

}

Output:输出:

contrived example undefined

in db: AutomationClient

Expected output:预期输出:

in db: AutomationClient

contrived example AutomationClient

Not sure why your main code passes in 2000 for the ms argument and then does a 5000ms timeout, in fact, why are you doing a timeout at all, if that was some attempt to wait for the db function to complete, then you don't need it不知道为什么您的主要代码为ms参数传入 2000 年,然后超时 5000 ms ,事实上,您为什么要超时,如果这是等待 db 函数完成的某种尝试,那么您不会不需要

If you must use promises - personally I'd use a simple callback for such simple code, however, I get that you want to learn how to use Promises如果你必须使用承诺——我个人会为这样简单的代码使用一个简单的回调,但是,我知道你想学习如何使用承诺

Your original code looked like it was attempting to return the value of the LAST row.name您的原始代码看起来像是试图返回LAST row.name的值

This code returns an array of row.name此代码返回一个row.name数组

Not knowing the type of data you'd be getting, I don't know which is correct不知道您将获得的数据类型,我不知道哪个是正确的

dbacess.js数据库

var Q = require('q');
var sql = require('mssql');

var config = {
    user: 'xx',
    password: 'xxx',
    server: 'aaa',
    database: 'RequestCenter',
    stream: true,

}

this.query1 = function() {
    var deferred = Q.defer();
    sql.connect(config, function(err) {
        var result = []; // return all rows - modify as required
        var request = new sql.Request();
        request.query("select * from dbo.AcAccount where Name like 'AutomationCli%' ");
        request.on('row', function(row) {
            console.log(row.Name);
            result.push(row.Name);
        });

        request.on('error', function(err) {
            console.log("err : " + err);
            deferred.reject(err);
        });

        request.on('done', function(returnValue) {
            deferred.resolve(result);
        });
    });

    sql.on('error', function(err) {
        console.log("sql err : " + err);
        deferred.reject(err);
    });
    return deferred.promise;
}

Code sample:代码示例:

db = require("./dbaccess.js");

db.query1().then(function(result) {
    console.log('contrived example ' + result);
});

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

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