首页 > 解决方案 > 在 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)
  });

标签: javascripthtmlcssfetch

解决方案


在下面试试这个。

如果您成功获得了获取用户位置的权限,那么这就是 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)
}

推荐阅读