[英]Node.js - request to database and delay
I have app on Node.js, consisting of two files. 我在Node.js上有app,由两个文件组成。 First file contains function with construction
if(..) { ... } else { ... }
, second file contains functions whose result in an argument in if()
and contains request to database. 第一个文件包含带构造函数
if(..) { ... } else { ... }
,第二个文件包含函数,其结果在if()
包含一个参数,并包含对数据库的请求。 Example: 例:
var args = require('./File_2');
if(args.test() && args.example()) {
//action
}
else {
//action
}
function test() {
mysql.query('SELECT * FROM `table` WHERE `name` = "test"', function(err, rows) {
if(rows.length == 0) {
return false;
}
else {
return true;
}
}
}
function example() {
mysql.query('SELECT * FROM `table` WHERE `name` = "example"', function(err, rows) {
if(rows.length == 0) {
return false;
}
else {
return true;
}
}
}
exports.test = test;
exports.example = example;
The request comes after some time, so in if()
arguments equal undefined, undefined
. 请求在一段时间后发生,所以
if()
参数等于undefined, undefined
。 How to make if/else
construction wait request result? 如何制作
if/else
构造等待请求结果? I have two ideas - promises and module async
. 我有两个想法 - 承诺和模块
async
。 I think async
- the wrong decision. 我认为
async
- 错误的决定。 How to use promises in this situation? 如何在这种情况下使用承诺? Which solution is preferable?
哪种解决方案更可取? I will be glad to any answers.
我会很高兴得到任何答案。
(Sorry for bad english.) (抱歉英语不好。)
async is a pretty awesome library, but in node you will use a callback (not a return). async是一个非常棒的库,但在节点中你将使用回调(而不是返回)。 Here is an example:
这是一个例子:
var async = require('async')
function test(callback){
//simulate one async method call
setTimeout(function(){
callback(null, "test_finished")
},100)
}
function example(callback){
//simulate another async method call
setTimeout(function(){
callback(null, "example finished")
},500)
}
function compare(err, results){
//results will maintain order of array in parallel
console.log(results[0], results[1]);
}
async.parallel([
example,
test
], compare);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.