0

这是一个更一般的 JS 问题,而不是特定于 edge.js。我想通过 edge.js 玩 SQL 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。我确定我做错了,但我看不到如何重组。有什么建议么?

4

1 回答 1

2

你不能“返回”它,你必须在回调中工作,就像 log 函数正在做的那样。

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.
于 2014-05-12T17:41:56.893 回答