2017-04-06 45 views
0

我需要通过HERE Map geocoder处理数据列表,以将locationId转换为坐标。 地理编码器类具有地理编码函数需要3个参数1个参数2. successCallFunction 3. failCallFunction。

self.geocodeByLocationIdByArray = function (locationIds, callback) 
      { 
       var deferred = $.Deferred(); 
       var result = []; 

       var convert = function() { 
        for (var i = 0; i < locationIds.length - 1; i++) 
        { 
         geocodingParameters = { 
          locationId: locationIds[i].locationId; 
         }; 
         self.geocoder.geocoder(geocodingParameters, onGeocodeSuccess, function() { }); 
        } 

       }; 

       convert(); 
       return deferred.promise(); 
      }; 

onGeocodeSuccess = function (result) { 

       var locations = result.Response.View[0].Result, 
        i; 
       var result = []; 
       // Add a marker for each location found 
       for (i = 0; i < locations.length; i++) { 
        result.push(new geoCoordinate(locations[i].Location.DisplayPosition.Latitude, locations[i].Location.DisplayPosition.Longitude)); 
       } 

       return result; 
      }; 

如何解决geocodeByLocationIdByArray功能等待,直到所有数据之前,并返回结果数组?我就那么一点点停止:(我的问题是,地理编码是异步。

+0

的[?我如何返回从一个异步调用的响应(可能的复制http://stackoverflow.com/questions/14220321/how-do-i-return-the-异步调用响应) –

+0

你不能,因为它是异步的。它看起来像你正在传递一个回调函数,为什么一旦你得到你的结果不调用该函数? –

+0

你选择使用'$ .Deferred'而不是ES6 Promise的任何原因? – trincot

回答

2

你可以promisify的地理编码方法,所以它没有得到一个回调作为参数,但返回一个承诺,那么你可以创建承诺的数组,每个这种新功能创建的。最后,你可以使用$.when等待所有这些承诺来解决,将结果连接并返回作为整个geocodeByLocationIdByArray方法的承诺值。

这是未经测试的代码,但您会发现:

self.geocodeByLocationIdByArray = function (locationIds) { 
    // Promisify geocoder: 
    function geocoderPromise(geocodingParameters) { 
     var deferred = $.Deferred(); 
     self.geocoder.geocoder(geocodingParameters, function() { 
      deferred.resolve(result); 
     }, function (err) { 
      deferred.reject(err); 
     }); 
     return deferred.promise(); 
    } 

    // Create an array of promises 
    var promises = locationIds.map(function (locationId) { 
     var geocodingParameters = { 
      locationId: locationIds[i].locationId; 
     }; 
     return geocoderPromise(geocodingParameters) 
      .then(onGeocodeSuccess) 
      .catch(function (err) { // or `fail` in jQuery < 3.0 
       console.log('geocoder error occurred', err); 
      }); 
    }); 
    // Wait for all promises to be resolved, and then concatenate the results 
    // as the final promised value. 
    return $.when.apply($, promises).then(function() { 
     return [].concat.apply([], arguments); 
    }); 
}; 

请注意,使用此代码不再有回调参数,但您需要将返回值geocodeByLocationIdByArray()作为承诺。所以,你可以这样写:

self.geocodeByLocationIdByArray([....ids....]).then(function (result) { 
    console.log(results); 
}); 
+0

谢谢。想法非常好! catch(function(err){console.log('geocoder error occurred,err); });它似乎是赶上不是一个函数 –

+0

啊是的,'catch'只在jQuery 3.0中引入。你可以放弃它,或者使用'fail'代替。 – trincot