我是NodeJs
中的新手我正试图从Node Js中的另一个函数获得响应。
我在Nodejs
中调用slug函数。我必须在插入之前获得slug但总是在做出回应undefined
我用的是noejs package slugs
var slugs = require("slugs");
我在打电话
genslug(user.name)
就像这样。
genslug(connection,slugs(user.name),1,slugs(user.name),callback)
像这样创建了一个函数genslug
var genslug = function(connection,slug,counter=1,orgSlug,callback) {
var query = connection.query('SELECT * FROM users WHERE slug = ?',slug,function(err,res) {
if(err)
callback({status: 'error', error : err});
if(res.length > 0){
counter++;
slug = orgSlug+'-'+counter;
genslug(connection,slug,counter,orgSlug,callback);
}else{
callback(false, slug);
}
});
}
但总是得到undefined
。
请回复如果有人知道这个
答案 0 :(得分:0)
Understand the callback nature.
First argument always takes as error
and second takes as success
.
In your case it always execute in error block from were you are calling the function since you are passing else
in final callback.
Try to remove
false
from final callback
var genslug = function(connection,slug,counter=1,orgSlug,callback) {
var query = connection.query('SELECT * FROM users WHERE slug = ?',slug,function(err,res) {
if(err)
callback({status: 'error', error : err});
if(res.length > 0){
counter++;
slug = orgSlug+'-'+counter;
genslug(connection,slug,counter,orgSlug);
}else{
callback(null, slug);
}
});
}
答案 1 :(得分:0)
.go