如何在Node.js模块中处理异步回调?

knu2xs

这是我尝试将节点模块组合在一起的第一步,而我仍在努力探索如何构造异步回调。这就是一个例子。现在,我正在尝试使用featureService.getCount()并且什么也没有得到回应。我知道使用断点featureService.getUniqueIds()是可行的。

由于其中存在回调,因此我假设未返回长度的原因是getCount中的回调尚未响应。在整个下午的大部分时间里都在看这个东西之后,除了递归循环检查要填充的超时值之外,并没有真正提出一个很好的解决方案,我想请教一些如何更好地构造代码以完成任务的建议在眼前。

我已经读过一些关于诺言的文章。这是适用实例还是可行的解决方案?我真的不知道如何实现承诺,但是在这种情况下这是合乎逻辑的。

显然我在这里迷路了。感谢您提供的任何帮助。

var Client = require('node-rest-client').Client;
var client = new Client();

var featureService = function(endpoint){

    var uniqueIds;
    var count;

    // get list of unique id's
    this.getUniqueIds = function(){
        if (!uniqueIds) {
            var options = {
                parameters: {
                    f: 'json',
                    where: "OBJECTID LIKE '%'",
                    returnIdsOnly: 'true'
                }
            };
            client.get(endpoint + '/query', options, function(data, res){
                var dataObject = JSON.parse(data);
                var uniqueIds = dataObject.objectIds;
                return uniqueIds;
            });
        } else {
            return uniqueIds;
        }
    };

    // get feature count
    this.getCount = function(){

        // get uniqueIds
        uniqueIds = this.getUniqueIds();

        // get length of uniqueIds
        count = uniqueIds.length;
    };

    // get list of unique attribute values in a single field for typeahead
    this.getTypeaheadJson = function(field){};

    // find features in a field with a specific value
    this.find = function(field, value){};
};

var endpoint = 'http://services.arcgis.com/SgB3dZDkkUxpEHxu/arcgis/rest/services/aw_accesses_20140712b/FeatureServer/1';
var afs = new featureService(endpoint);
console.log(afs.getCount());

exports.featureService = featureService;

现在,在处理了更多内容并request按照bluebird文档中的内容使用后(我无法使上述模块正常工作),我可以进行此工作,但无法弄清楚如何获得计算值以及迭代次数。

var Promise = require("bluebird"),
    request = Promise.promisifyAll(require("request"));

var FeatureService = function(){

    // get count from rest endpoint
    var getCount = function(){
        var optionsCount = {
            url: endpoint + '/query',
            qs: {
                f: 'json',
                where: "OBJECTID LIKE '%'",
                returnCountOnly: 'true'
            }
        };
        return request.getAsync(optionsCount)
            .get(1)
            .then(JSON.parse)
            .get('count');
    };

    // get max record count for each call to rest endpoint
    var getMaxRecordCount = function(){
        var optionsCount = {
            url: endpoint,
            qs: {
                f: 'json'
            }
        };
        return request.getAsync(optionsCount)
            .get(1)
            .then(JSON.parse)
            .get('maxRecordCount');
    };

    // divide the total record count by the number of records returned per query to get the number of query iterations
    this.getQueryIterations = function(){
        getCount().then(function(count){
            getMaxRecordCount().then(function(maxCount){
                return  Math.ceil(count/maxCount);
            });
        });
    };

};

// url to test against
var endpoint = 'http://services.arcgis.com/SgB3dZDkkUxpEHxu/arcgis/rest/services/aw_accesses_20140712b/FeatureServer/1';

// create new feature service object instance
afs = new FeatureService();

// This seems like it should work, but only returns undefined
console.log(afs.getQueryIterations());

// this throws an error telling me "TypeError: Cannot call method 'then' of undefined"
//afs.getQueryIterations().then(function(iterCount){
//    console.log(iterCount);
//});
贝吉

是的,使用诺言!它们是一个功能强大的工具,正是为此目的而制作的,并且具有不错的库,易于使用。在您的情况下:

var Promise = require('bluebird'); // for example, the Bluebird libary
var Client = Promise.promisifyAll(require('node-rest-client').Client);
var client = new Client();

function FeatureService(endpoint) {

    var uniqueIds;
    var count;

    // get list of unique id's
    this.getUniqueIds = function(){
        if (!uniqueIds) { // by caching the promise itself, you won't do multiple requests
                          // even if the method is called again before the first returns
            uniqueIds = client.getAsync(endpoint + '/query', {
                parameters: {
                    f: 'json',
                    where: "OBJECTID LIKE '%'",
                    returnIdsOnly: 'true'
                }
            })
            .then(JSON.parse)
            .get("objectIds");
        }
        return uniqueIds;
    };

    // get feature count
    this.getCount = function(){
        if (!count)
            count = this.getUniqueIds() // returns a promise now!
                    .get("length");
        return count; // return a promise for the length
    };

    // get list of unique attribute values in a single field for typeahead
    this.getTypeaheadJson = function(field){};

    // find features in a field with a specific value
    this.find = function(field, value){};
};

var endpoint = 'http://services.arcgis.com/SgB3dZDkkUxpEHxu/arcgis/rest/services/aw_accesses_20140712b/FeatureServer/1';
var afs = new FeatureService(endpoint);
afs.getCount().then(function(count) {
    console.log(count);
}); // you will need to use a callback to do something with async results (always!)

exports.FeatureService = FeatureService;

在这里,使用Bluebird的Promise.promisifyAll,您可以使用.getAsync()代替.get(),并且可以保证结果。


// divide the total record count by the number of records returned per query to get the number of query iterations
this.getQueryIterations = function(){
    getCount().then(function(count){
        getMaxRecordCount().then(function(maxCount){
            return  Math.ceil(count/maxCount);
        });
    });
};

那是正确的主意!只有您始终希望return.then处理程序中得到一些东西,以便.then()调用返回的promise将使用该值进行解析。

// divide the total record count by the number of records returned per query to get the number of query iterations
this.getQueryIterations = function(){
    return getCount().then(function(count){
//  ^^^^^^ return the promise from the `getQueryIterations` method
        return getMaxRecordCount().then(function(maxCount){
//      ^^^^^^ return the promise for the iteration number
            return  Math.ceil(count/maxCount);
        });
    });
};

现在,您将获得对最内在结果承诺,这将立即起作用:

afs.getQueryIterations().then(function(iterCount){
    console.log(iterCount);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章