这更多的是一个通用的JS问题,而不是专门针对edge.js的。我想通过edge.js使用Server访问。基于来自其GitHub站点的以下片段
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内部推到它。我肯定我做错了,但我不知道怎么重组。有什么建议吗?
发布于 2014-05-12 17:41:56
您不能“返回”它,您必须在回调中工作,就像日志函数所做的那样。
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;
});
};现在,您可以将其用作Array或在每个数组中使用:
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.https://stackoverflow.com/questions/23614801
复制相似问题