如何在javascript

时间:2015-06-12 12:50:40

标签: javascript dojo deferred arcgis-js-api

我正在尝试编写一个将坐标投影到新的空间参考中的模块,但javascript语法再次击败了我。

这就是模块目前的样子:

define(["esri/geometry/Point", ...], 
    function(Point, SpatialReference, ...){

    var gmsvc = new GeometryService("http://server/maps/rest/services/Utilities/Geometry/GeometryServer");
    /*...*/

    return {
        /*...*/
        //transforms the current point on the map to the new wkid
        transformCoordinates: function(point, newWkId) {

            var param = new ProjectParameters();
            var newPoint;
            param.geometries = [point];
            param.outSR = new SpatialReference({ wkid: newWkId});

            gmsvc.project(param);

            gmsvc.on('project-complete', function(result) {
                newPoint = result.geometries[0];
            });

            return newPoint;
        }   
    };
});

根据documentation GeometryService.project(parameter)被标记为延迟,因此我尝试在OnProjectComplete事件中访问它的结果。此时result.geometries[0]是具有x,y和SpatialReference属性的有效Point。 将其分配给newPoint变量并将其返回,会导致返回undefined

console.log(CoordinateTransUtils.transformCoordinates(evt.mapPoint, 5254));
> undefined

将代码更改为

return gmsvc.on('project-complete', function(result) {
    return result.geometries[0];
});

返回值为:

Object {id: 216, receiveArguments: true, previous: Object}advice: (){var b,c={},e=arguments.length;for(b=0;b<e;b++)c[f[b]]=arguments[b];c.target||(c.target=d);a.call(d,c)}id: 216next: Objectprevious: ObjectreceiveArguments: trueremove: (){if(h.advice){var c=h.previous,d=h.next;!d&&!c?delete b[e]:(c?c.next=d:b[e]=d,d&&(d.previous=c));b=a=h.advice=null}}__proto__: Object

这也不是重点。 因此,我的问题是,如何返回result.geometries[0]中存储的点,并解释我在这里做错了什么。

1 个答案:

答案 0 :(得分:1)

在您的示例中,newPoint仅在已经处理return语句后实际设置,因此在该行运行时未定义。

通常,如果函数逻辑中的某些内容是异步的,那么您的函数本身也需要是异步的。通常在这些情况下,建议返回承诺。 e.g:

    transformCoordinates: function(point, newWkId) {
        var dfd = new Deferred(); // (from dojo/Deferred)
        var param = new ProjectParameters();
        param.geometries = [point];
        param.outSR = new SpatialReference({ wkid: newWkId});

        gmsvc.project(param);

        gmsvc.on('project-complete', function(result) {
            dfd.resolve(result.geometries[0]);
        });
        // If there is an accompanying error event, you should also
        // listen to that and call dfd.reject in its handler.

        return dfd.promise;
    }

有关详细信息,请参阅DeferredPromise教程。