这是一个更普遍的JS问题,并不是特定于edge.js.我想通过edge.js玩SQL Server访问。基于the following snippet from its GitHub site
var edge = require('edge');
var getTop10Products = edge.func('sql', function () {/*
select top 10 * from Products
*/});
getTop10Products(null, function (error, result) {
if (error) throw error;
console.log(result);
console.log(result[0].ProductName);
console.log(result[1].ReorderLevel);
});
我写了以下内容来访问我自己的数据库:
var edge = require('edge');
var _ = require('lodash');
var thingsAccess = function () {/*
select * from Things where Status = 'A' and Type=@thingType
*/};
var getThingsList = edge.func('sql', thingsAccess);
var logResult = function (error, result) {
if (error) throw error;
_.each(result, function (thing) {
console.log(thing.Id, thing.Category, thing.Name);
});
};
var thingsOfType = function (type) {
return function () {
getThingsList({ thingType: type }, logResult);
};
};
var xThings = thingsOfType('X');
var yThings = thingsOfType('Y');
xThings();
yThings();
我的问题是,如何从logResult
返回结果而不仅仅是使用该函数中的数据?而不是现在登录到控制台的_.each(result, ...)
构造,而是像return _.map(result, ...)
那样返回Thing对象的数组。但是因为函数是getThingsList的回调函数,所以无处可放。
鉴于我如何构造代码,似乎我唯一的选择是在外部作用域中声明一个数组并从logResult
内部推送到它。我确定我做错了,但我看不出如何重组。有什么建议吗?
答案 0 :(得分:2)
你不能"返回"它,你必须在回调中工作,就像日志功能一样。
var thingsOfType = function (type, onSuccess, onError) {
getThingsList({ thingType: type }, function (error, result) {
// Process if no error
if (!error) {
if (onSuccess instanceof Function) {
onSuccess(result);
}
// silently do nothing if onSuccess is not a function
return;
}
// Handle errors using the onError callback or throw
if (onError instanceof Function) {
onError(error, result);
return;
}
// unhandled errors
throw error;
});
};
现在您可以将它用作数组或在每个数据库中使用:
thingsOfType("X", function (result) {
// Here result should be an Array
var len = result.length;
// You can use result here with or without _.each
// Do something here
} /*, not an onError function defined */ );
示例用法,以及如何进一步使用事件驱动代码:
var printAllThingsOf = function (type, onSuccess, onError) {
thingsOfType(type, function (result) {
// Print each one
_.each(result, function (thing) {
console.log(thing.Id, thing.Category, thing.Name);
});
// this function is the thingsOfType-onSuccess function,
// so propagate the new printAllThingsOf-onSuccess function;
// "call the callback"
if (onSuccess instanceof Function) {
onSuccess(result);
}
}, onError /* propagate the onError */ );
};
printAllThingsOf("X"); // just do it or fail. onSuccess and onError are undefined.