kay*_*asa 3 javascript json node.js express
我在NodeJS Express中定义了一个路由.
该路由多次调用一个函数(返回一个promise).从这些Promises返回的值被添加到一个Array,然后使用res.json()将其发送回客户端.
我面临的问题是,当Promise得到解决时,res.json()会执行,因为它不会等待Promises返回.我认为需要某种链接机制,但无法弄清楚如何做到这一点.
以下是我的代码
app.get('/markers', function(req, res) {
var markers = [];
var marker1 = {"id": 1, "name": "London"};
// Get the lat and lng based on the address
geocoding(marker1.name).then(function(geocode) {
marker1.lat = geocode[0].latitude;
marker1.lng = geocode[0].longitude;
markers.push(marker1);
}, function(error) {
console.log(error);
})
var marker2 = {"id": 2, "name": "Chicago" };
geocoding(marker2.name).then(function(geocode) {
marker2.lat = geocode[0].latitude;
marker2.lng = geocode[0].longitude;
markers.push(marker2);
}, function(error) {
console.log(error);
})
var marker3 = {"id": 3, "name": "Munich" };
geocoding(marker3.name).then(function(geocode) {
marker3.lat = geocode[0].latitude;
marker3.lng = geocode[0].longitude;
markers.push(marker3);
}, function(error) {
console.log(error);
})
// return the lat and lng array to the client
res.json(markers);
})
Run Code Online (Sandbox Code Playgroud)
我怎样才能确保'res.json(markers);' 在解决了所有三个Promise之后执行.
您只需使用Promise.all,将在所有承诺解决时解决:
app.get('/markers', function(req, res) {
var markers = [];
var marker1 = {"id": 1, "name": "London"};
// Get the lat and lng based on the address
var prom1 = geocoding(marker1.name).then(function(geocode) {
marker1.lat = geocode[0].latitude;
marker1.lng = geocode[0].longitude;
markers.push(marker1);
}, function(error) {
console.log(error);
})
var marker2 = {"id": 2, "name": "Chicago" };
var prom2 = geocoding(marker2.name).then(function(geocode) {
marker2.lat = geocode[0].latitude;
marker2.lng = geocode[0].longitude;
markers.push(marker2);
}, function(error) {
console.log(error);
});
var marker3 = {"id": 3, "name": "Munich" };
var prom3 = geocoding(marker3.name).then(function(geocode) {
marker3.lat = geocode[0].latitude;
marker3.lng = geocode[0].longitude;
markers.push(marker3);
}, function(error) {
console.log(error);
});
// return the lat and lng array to the client
Promise.all([prom1, prom2, prom3]).then(function() {res.json(markers);}).catch(function(err) {console.error(err);});
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4344 次 |
| 最近记录: |