如何将Post Route功能调用以获取API数据(JS)?

发布于 2025-02-08 02:31:35 字数 2894 浏览 2 评论 0原文

当我访问(由于缺乏更好的术语)“/postuserinput”后路由时,它要么不运行getgeOnamesdata()直到结束,要么不等待API提取完成。我从此功能中获得的数据用于同时调用。

我该怎么做才能确保这些功能按顺序运行?

这是我的服务器文件代码。它按照控制台按此顺序运行:

首先 第三 第四 第五 第六 第七 特征 其次,

这使我剩下的所有API呼叫无法获得正确的数据。请帮忙。

谢谢。


app.post('/postUserInput', function (req, res) {
  currentWeatherUI = req.body.buildCurrentBoolean;
  userInput = {
    userCityInput: req.body.userCityInput, 
    userStateInput: req.body.userStateInput, 
    userDateInput: req.body.userDateInput,
  };
  console.log("first");
  getGeoNamesData();

  console.log("third");

  if (currentWeatherUI) {
    getCurrentWeatherbitData(longitude, latitude);
    console.log("fifth");
  } else {
    getFutureWeatherbitData(longitude, latitude);
  };
  console.log("sixth");
  getPixabayData();
  console.log("eigth");
});

const getGeoNamesData = async () => {
  try{
  const response = await axios.get('http://api.geonames.org/searchJSON?q='+userInput.userCityInput+'+'+userInput.userStateInput+'&maxRows=1&username='+geonamesUser);

    longitude = response.data.geonames[0].lng
    latitude = response.data.geonames[0].lat

    console.log("second");
  } catch(error) {
      console.log("error2", error);
  };
};

const getCurrentWeatherbitData = async (longitude, latitude) => {
  try {
    const weatherbitURL = "http://api.weatherbit.io/v2.0/current?&lat="+latitude+"&lon="+longitude+"&key="+weatherbitUser+"&units=I&lang=en";
    const response = await axios.get(weatherbitURL);
    let newDayObject = {
      city: response.data.data[0].city_name,
      state: response.data.data[0].state_code,
      date: userInput.userDateInput,
      temp: response.data.data[0].temp,
      wind: response.data.data[0].wind_spd,
      windDirection: response.data.data[0].wind_cdir,
      rain: response.data.data[0].precip,
      snow: response.data.data[0].snow
    };
    projectDataArray.push(newDayObject);
    console.log("fourth");
  } catch(error) {
      console.log("error", error);
  };
};

const getPixabayData = async () => {
  try {
    const pixabayURL = "https://pixabay.com/api/?key="+pixabayUser+"&q="+userInput.userCityInput+"+"+userInput.userStateInput+"&image_type=photo&pretty=true&per_page=3";
    const response = await axios.get(pixabayURL);
    if (response.data.hits.length > 0) {
      let cityImageObj = {cityImageURL: response.data.hits[0].webformatURL};
      projectDataArray.push(cityImageObj);
    } else {
      let cityImageObj = {cityImageURL: "https://www.pennlive.com/resizer/vNu0aYjk3xlFTUb16FSrSji_DIA=/1280x0/smart/advancelocal-adapter-image-uploads.s3.amazonaws.com/image.pennlive.com/home/penn-media/width2048/img/life/photo/wintermeme11.jpg"};
      projectDataArray.push(cityImageObj);
    }
    console.log("seventh");
  } catch(error) {
      console.log("error", error);
  }; 
};```

When I access(for lack of a better term) the '/postUserInput' POST route, it either does not run getGeoNamesData() until the end, or it doesn't wait for the API fetch to finish. The data I get from this function is used for simultaneous API calls.

What should I do to make sure these functions run in order?

This is my server file code. It runs in this order according to the console:

first
third
fourth
fifth
sixth
seventh
eigth
second

This keeps all my remaining API calls from having the correct data. Please help.

Thanks.


app.post('/postUserInput', function (req, res) {
  currentWeatherUI = req.body.buildCurrentBoolean;
  userInput = {
    userCityInput: req.body.userCityInput, 
    userStateInput: req.body.userStateInput, 
    userDateInput: req.body.userDateInput,
  };
  console.log("first");
  getGeoNamesData();

  console.log("third");

  if (currentWeatherUI) {
    getCurrentWeatherbitData(longitude, latitude);
    console.log("fifth");
  } else {
    getFutureWeatherbitData(longitude, latitude);
  };
  console.log("sixth");
  getPixabayData();
  console.log("eigth");
});

const getGeoNamesData = async () => {
  try{
  const response = await axios.get('http://api.geonames.org/searchJSON?q='+userInput.userCityInput+'+'+userInput.userStateInput+'&maxRows=1&username='+geonamesUser);

    longitude = response.data.geonames[0].lng
    latitude = response.data.geonames[0].lat

    console.log("second");
  } catch(error) {
      console.log("error2", error);
  };
};

const getCurrentWeatherbitData = async (longitude, latitude) => {
  try {
    const weatherbitURL = "http://api.weatherbit.io/v2.0/current?&lat="+latitude+"&lon="+longitude+"&key="+weatherbitUser+"&units=I&lang=en";
    const response = await axios.get(weatherbitURL);
    let newDayObject = {
      city: response.data.data[0].city_name,
      state: response.data.data[0].state_code,
      date: userInput.userDateInput,
      temp: response.data.data[0].temp,
      wind: response.data.data[0].wind_spd,
      windDirection: response.data.data[0].wind_cdir,
      rain: response.data.data[0].precip,
      snow: response.data.data[0].snow
    };
    projectDataArray.push(newDayObject);
    console.log("fourth");
  } catch(error) {
      console.log("error", error);
  };
};

const getPixabayData = async () => {
  try {
    const pixabayURL = "https://pixabay.com/api/?key="+pixabayUser+"&q="+userInput.userCityInput+"+"+userInput.userStateInput+"&image_type=photo&pretty=true&per_page=3";
    const response = await axios.get(pixabayURL);
    if (response.data.hits.length > 0) {
      let cityImageObj = {cityImageURL: response.data.hits[0].webformatURL};
      projectDataArray.push(cityImageObj);
    } else {
      let cityImageObj = {cityImageURL: "https://www.pennlive.com/resizer/vNu0aYjk3xlFTUb16FSrSji_DIA=/1280x0/smart/advancelocal-adapter-image-uploads.s3.amazonaws.com/image.pennlive.com/home/penn-media/width2048/img/life/photo/wintermeme11.jpg"};
      projectDataArray.push(cityImageObj);
    }
    console.log("seventh");
  } catch(error) {
      console.log("error", error);
  }; 
};```

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡墨 2025-02-15 02:31:35

请检查

异步函数可以包含零或更多等待的表达式。等待表达使承诺的返回功能的行为似乎是通过暂停执行,直到返回的诺言被履行或拒绝。

这应该运行功能-GetGeonamesdata,GetCurrentWeatherBitdata getPixaBayData,以便您期望。

app.post("/postUserInput", async function (req, res) {
  currentWeatherUI = req.body.buildCurrentBoolean;
  userInput = {
    userCityInput: req.body.userCityInput,
    userStateInput: req.body.userStateInput,
    userDateInput: req.body.userDateInput,
  };
  console.log("first");
  await getGeoNamesData();

  console.log("third");

  if (currentWeatherUI) {
    await getCurrentWeatherbitData(longitude, latitude);
    console.log("fifth");
  } else {
    await getFutureWeatherbitData(longitude, latitude);
  }
  console.log("sixth");
  await getPixabayData();
  console.log("eigth");
});

Please check the MDN Docs for async functions in Javascript.
According to the docs:

Async functions can contain zero or more await expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected.

This should run the functions - getGeoNamesData, getCurrentWeatherbitData getPixabayData in order that you expect.

app.post("/postUserInput", async function (req, res) {
  currentWeatherUI = req.body.buildCurrentBoolean;
  userInput = {
    userCityInput: req.body.userCityInput,
    userStateInput: req.body.userStateInput,
    userDateInput: req.body.userDateInput,
  };
  console.log("first");
  await getGeoNamesData();

  console.log("third");

  if (currentWeatherUI) {
    await getCurrentWeatherbitData(longitude, latitude);
    console.log("fifth");
  } else {
    await getFutureWeatherbitData(longitude, latitude);
  }
  console.log("sixth");
  await getPixabayData();
  console.log("eigth");
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文