好吧,我实际上正在使用谷歌服务来计算一些 map 路线。我已将其放入一项服务中,代码为:
const directionsService = new google.maps.DirectionsService();
directionsService.route(route, (data, status) => {
if (status === 'OK') {
this.storage.routeValue = data.routes[0].legs[0].duration.value;
}
});
}
我从不同的页面将数据传递到该服务,它所做的就是根据数据(纬度和经度)给出的数据计算路线并将其返回。 我面临的问题是,我还在当前页面中执行了其他几项操作,将本地值更改为某些变量。所以我有这样的东西:
//This calls the code from above and pass the data from my page to the service:
this.googledirectionsService.route(data);
///I now have:
this.isStarted = true;
this.map.showPath();
所以我调用另一个函数,然后更改局部变量。但我不知道其他服务什么时候完成。 我可以用什么来改进这段代码?可观察到的? 我需要能够知道代码何时以及如何从我的 googledirectionsService 完成,然后从当前页面中执行其他代码。 我可以在服务中的路由回调中放置一个公共(public)变量,然后检查当前页面,但问题是这可能需要 2 秒、5 秒……如果数据错误,甚至会更长,所以我需要能够首先知道我的服务的结果是什么,然后继续使用其他代码。
最佳答案
在取回数据后,您可以使用 Promise 并执行新操作。
// your service code
const directionsService = new google.maps.DirectionsService();
const route = (route) => {
return new Promise((resolve, reject) => {
return directionsService.route(route, (data, status) => {
if (status === 'OK') {
this.storage.routeValue = data.routes[0].legs[0].duration.value;
return resolve("your success message")
} else {
return reject("your error")
}
});
});
};
// your current file
this.googledirectionsService.route(data).then(success => {
this.isStarted = true;
this.map.showPath();
}).catch(error => {
console.log("error", error)
});
请告诉我这是否有效。
关于javascript - 从另一页面中的一项服务的回调函数获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61305495/