2017-02-27 54 views
2

我在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中。字符串有價值,但在外面,結果它只是"{}"

我該如何正確使用這些承諾?

+0

您需要等待異步代碼才能完成 –

+0

而不是手動創建JSON字符串,可能會更容易創建具有所需屬性的對象,然後調用'JSON.stringify'以確保所有內容格式正確。您當前的代碼不會轉義引號。 – 4castle

+0

JSON字符串只是一個例子,我正在學習如何承諾工作 –

回答

1

簡單的方法是如果你使用最新的使用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); 
}); 
+0

謝謝,這真的幫助我瞭解承諾 –

0

試試這個:

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,你可以看看this