我想按顺序执行查询,但我不知道最好的方法是什么。
假设我想执行以下操作:
if (name) {
//first query
db.query({name:name}).exec(function(err,result) {
//save result
})
}
if (isEmpty(result)) {
//make another query
db.query({anotherField:value}).exec(function(err,result) {
//save result
})
}
在这种情况下我应该使用 promise 吗?
这将是 cakePHP 的一个示例:
if (!isset($field1)) {
$result = $this->item->find( ... conditions => ... = $field2);
} else {
if (!isset($field2)) {
$result = $this->item->find( ... conditions => ... = $field1);
} else {
$result = $this->item->find( ... conditions => ... = $field1 && ... =$field2);
if (empty($result)) {
$result = $this->item->find( ... conditions => ... =$field2);
}
}
}
最佳答案
如果您的意思是“按顺序”,您可以嵌套回调。传递回调是构造异步代码的经典(非 promise )方法:
function doMultipleAsyncThings(name, callback){
if (name) {
//first query
db.query({name:name}).exec(function(err,result) {
if (isEmpty(result)) {
//make another query
db.query({anotherField:value}).exec(function(err,result) {
//save result
})
} else {
//save result
}
})
} else {
return callback('no name');
}
}
注意,在超过 2 次左右的操作之后,您最终会陷入 100 多行嵌套代码的“回调 hell ”,即 async图书馆对此很有帮助:
var async = require('async');
doMultipleAsyncThings('plato', function(){
console.log(arguments)
});
function doMultipleAsyncThings(name, callback){
// `callback` is a passed-in function to call after doMultipleAsyncThings is done
// Here, it is the function we passed in above after 'plato'
async.waterfall([function(done){
done(null, name);
},
firstQuery,
secondQuery,
], callback)
}
function firstQuery(name, done){
if (name) {
// You can define and pass a callback inline:
db.query({name:name}).exec(function(err,result) {
done(err, result);
})
} else {
done('no name');
}
}
function secondQuery(result, done){
if (isEmpty(result)) {
// You can pass a callback by reference:
db.query({anotherField:value}).exec(done)
} else {
//save result
done();
}
}
关于Node.js 数据库按顺序查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31279974/