Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make string with Promises in Node JS

I have a question with promises in Node JS. I need to make a JSON string with some data coming from two promises, but it does not make right. This is my code:

var aux = "{";

geocoder.reverse(initPointReversing)
  .then(function(initData) {
    aux += "originAddress:'" + initData[0].formattedAddress + "',";
  })
  .catch(function(err) {
    console.log(err);
  });

geocoder.reverse(endPointReversing)
  .then(function(endData) {
    aux += "destinationAddress:'" + endData[0].formattedAddress + "',";
  })
  .catch(function(err2) {
    console.log(err2);
  });

aux += "}";

Inside the promises. the strings have value, but outside, the result it's only "{}"

How can I need to use these promises correctly?

like image 610
David Perez Avatar asked Jul 10 '26 03:07

David Perez


1 Answers

Simplest way is to use Promise.all

var p1 = geocoder.reverse(initPointReversing)
.then(function(initData) {
    return initData[0].formattedAddress;
});

var p2 = geocoder.reverse(endPointReversing)
.then(function(endData) {
    return endData[0].formattedAddress;
});

Promise.all([p1, p2]).then(function(results) {
    var t = {originAddress: results[0], destinationAddress: results[1]};
    var aux = JSON.stringify(t);
})
.catch(function(err) {
    console.log(err);
});

If you're using the latest node,

var p1 = geocoder.reverse(initPointReversing).then(initData => initData[0].formattedAddress);
var p2 = geocoder.reverse(endPointReversing).then(endData => endData[0].formattedAddress);

Promise.all([p1, p2]).then(([originAddress, destinationAddress]) => {}
    var aux = JSON.stringify({originAddress, destinationAddress});
    // do things
})
.catch(function(err) {
    console.log(err);
});
like image 80
Jaromanda X Avatar answered Jul 13 '26 20:07

Jaromanda X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!