我在Node JS中有一個承諾問題。 我需要製作一個JSON字符串,其中包含來自兩個promise的一些數據,但它並不正確。這是我的代碼:用節點JS中的承諾生成字符串
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 += "}";
在promise中。字符串有價值,但在外面,結果它只是"{}"
我該如何正確使用這些承諾?
您需要等待異步代碼才能完成 –
而不是手動創建JSON字符串,可能會更容易創建具有所需屬性的對象,然後調用'JSON.stringify'以確保所有內容格式正確。您當前的代碼不會轉義引號。 – 4castle
JSON字符串只是一個例子,我正在學習如何承諾工作 –