在节点JS中用Promise创buildstring

我有一个在节点JS承诺的问题。 我需要制作一个JSONstring,其中包含来自两个promise的一些数据,但是它并不正确。 这是我的代码:

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 += "}"; 

在承诺之内。 string有价值,但在外面,结果它只是"{}"

我该如何正确使用这些承诺?

最简单的方法是使用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); }); 

如果您正在使用最新的节点,

 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); }); 

尝试这个:

 Promise.all([geocoder.reverse(initPointReversing),geocoder.reverse(endPointReversing)]) .then(function(values) { aux = "{"; aux += "originAddress:'" + values[0][0].formattedAddress + "',"; aux += "destinationAddress:'" + values[1][0].formattedAddress + "',"; aux = "}"; }) .catch(function (err) { console.log(err); }); 

如何使用Promise.all ,你可以看看这个