javascript - 从另一个页面中的一个服务的回调函数获取结果
问题描述
好的,所以我实际上是在使用谷歌服务来计算一些地图路线。我已将其放在一项服务中,代码为:
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 完成,而不是从当前页面执行其他代码。我可以在服务的路由回调中放置一个公共变量,然后检查我的当前页面,但问题是这可能需要 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)
});
请让我知道这是否有效。
推荐阅读
- samesite - 启动 chrome 时禁用“没有 SameSite 的 Cookie 必须是安全的”的标志
- android - TextView Wrap_Content 高度在某些分辨率下不起作用
- python - 删除重复但优先在熊猫中保持第一
- javascript - 如何加速大量画布渲染
- ios - 子类中的空白函数是否符合自定义协议?
- python - 传递登录凭据时,在iis上运行的python烧瓶网站未连接到sql数据库
- javascript - 在 node.js 中使用 Fetch API 记录 HTTP 错误
- javascript - Mongoose 和多次保存错误处理
- azure - Azure Blob 存储 CDN 在不存在时询问 favicon.ico?
- python - 给定等边三角形的 2D 角坐标的 3D 法线向量