javascript - 在 fetch 调用之前运行函数?
问题描述
我一直在尝试创建一个 vanilla js 天气应用程序,该应用程序在获得许可的情况下获取用户位置,并将其作为模板字符串输入到 fetch 调用中,然后天气应用程序将推断那里的位置并返回温度。
我仍然相对较新,并且遇到了障碍,我注意到 fetch 调用在用户能够单击允许获取位置的按钮之前运行。
无论如何要暂停 fetch 调用,直到函数运行之后?我可以使用附加到函数的 onclick 来运行 fetch 调用吗?
var latitude,longitude;
function allow() {
navigator.geolcation;
navigator.geolocation.getCurrentPosition(currentPosition);
};
function currentPosition(position) {
latitude = (position.coords.latitude);
longitude = (position.coords.longitude);
};
function onPositionReady() {
console.log(latitude,longitude);
// proceed
};
let api = {
key:'456fa9bb93098fb3454b25380512d491',
};
fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
.then(response => response.json())
.then(data => {
// Here's a list of repos!
console.log(data)
});
解决方案
在下面试试这个。
如果您成功获得了获取用户位置的权限,那么这就是 long/lat 变得可用的时候。在它们可用的同时,您可以运行 fetch 调用。
如果用户拒绝您使用该位置,那么它将触发该error
功能。
在此处了解更多信息https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
function success(pos) {
var crd = pos.coords;
let api = {
key:'456fa9bb93098fb3454b25380512d491',
};
fetch(`https://api.openweathermap.org/data/2.5/onecall? lat=${crd.latitude}&lon=${crd.longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
.then(response => response.json())
.then(data => {
// Here's a list of repos!
console.log(data)
});
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
如果为了便于阅读,您不想直接在success()
方法中直接获取 fetch(假设您要向其中添加更多代码),您可以将其包装在成功函数之外的自己的函数中,然后success()
像这样在函数中调用它
function doRequest(crd) {
let api = {
key: '456fa9bb93098fb3454b25380512d491',
};
fetch(`https://api.openweathermap.org/data/2.5/onecall? lat=${crd.latitude}&lon=${crd.longitude}&exclude=minutely,hourly,daily&appid=${api.key}&units=imperial`)
.then(response => response.json())
.then(data => {
// Here's a list of repos!
console.log(data)
});
}
function success(pos) {
var crd = pos.coords;
doRequest(crd)
}
推荐阅读
- typescript - 为什么 Rollup 试图将我的依赖项的 TypeScript 解析为 JavaScript?
- flutter - Firebase 存储身份验证
- node.js - Nodejs,需要时间的多个请求
- mysql - 在 Xampp 中的 2 个相同安装之间复制数据文件夹后无法启动 MySql
- java - Java - 使用用户表单输入将图像上传到网站,将它们保存在 MySQL 数据库中,并在网站上显示图像
- javascript - 将值推送到状态时,我在 React Native 上遇到错误
- c# - 文字在 2 秒后持续闪烁。协程
- python - 根据列值对数据框的行进行样式设置
- android - 如何将 ListView.builder 和其他小部件与 Flutter 对齐
- python - Python MP3 播放器 tkinter 崩溃