0

How can I return the value of reverseGeocodeData using a promise (using the resolve method in the promise)?

geocoder.reverseGeocode(33.7489, -84.3789,function (err, reverseGeocodeData){
    //something;
},
// Reverse Geocoding
return new Promise(function(resolve,reject){
    resolve();
});
István
  • 5,057
  • 10
  • 38
  • 67
codejunkie
  • 908
  • 2
  • 21
  • 34
  • @Quentin this isn't a duplicate for that question, the issue is how to promisify an async function that takes a callback. – robertklep Jun 22 '16 at 12:36
  • let geocode = (lat, long)=>geocoder.reverse(lat, long, (err, data)=> new Promise((resolve, reject)=>if(err) return reject(err); resolve(data) )) – Jose Hermosilla Rodrigo Jun 22 '16 at 12:37
  • @Quentin a possible solution using promises is given, along a whole lot of other solutions to explain how to return a value _in general_. But IMO this isn't a general question about how to handle return values for async functions, but specifically how to wrap an async function with a promise. – robertklep Jun 22 '16 at 12:40
  • @robertklep — The answer to the duplicate question still answers the specific question here. – Quentin Jun 22 '16 at 12:41
  • @Quentin but the _question_ isn't the same. – robertklep Jun 22 '16 at 12:42
  • @robertklep — It doesn't need to be perfectly identical. It's the same as part of the duplicate question and the answers to the duplicate answer this question. – Quentin Jun 22 '16 at 12:44
  • @Quentin in that case, feel free to reclose it as a duplicate, I won't reopen it (although I don't agree :) – robertklep Jun 22 '16 at 12:45
  • I can't. The system prevents me from doing that to avoid open/close wars. It needs someone who hasn't been involved in the moderation process yet to close it. – Quentin Jun 22 '16 at 12:46

2 Answers2

0

You have to resolve or reject the promise in the callback of the goecoder...

return new Promise(function(resolve, reject) {
    geocoder.reverseGeocode(33.7489, -84.3789, function (err, reverseGeocodeData) {
         if(err) return reject(err);
         resolve(reverseGeocodeData);
    });
});

This would be the basic implementation of a Promise. Depending on the promise library you're using there are of course other options. I prefer bluebird or when

bflemi3
  • 6,698
  • 20
  • 88
  • 155
-1

this is an example using bluebird.js (http://bluebirdjs.com/docs/api/promise.promisify.html)

var Promise = require('bluebird');
var reverseGeocodePromise = Promise.promisify(geocoder.reverseGeocode);

reverseGeocodePromise(33.7489, -84.3789)
  .then(function(result) {
    // do something;
  })
  .catch(function(err) {
    // handle error
  })
Alongkorn
  • 3,968
  • 1
  • 24
  • 41