簡體   English   中英

鏈接異步函數無法正常工作

[英]Chaining async functions doesn't work correctly

我正在嘗試鏈接兩個異步函數,但似乎第二個函數在第一個函數之前執行。 這是我的代碼

function performAction(e) {
const ZIP = document.getElementById('zip').value;
const fellings = document.getElementById('feelings').value;
console.log(`${baseURL}${ZIP},us&appid=${key}`);
getWeather(baseURL, ZIP, key,).then((data) => {
    postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings })
}).then(
    updateUI()
)}

這是 getWeather()

const getWeather = async(baseURL, ZIP, key) => {
let URL = `${baseURL}${ZIP}&appid=${key}`;
const res = await fetch(URL)
try{
    const data = await res.json();
    return data;
}catch(error){
    console.log("error", error);
}}

這是 postData() ,它應該在 getWeather function 被執行后執行,但事實並非如此。

const postData = async ( url = '', data = {}) => {
console.log(`This is what we fetch ${data.temperature}`);
console.log(`This is what we fetch ${data.date}`);
console.log(`This is what we fetch ${data.userResponse}`);
  const response = await fetch(url, {
  method: 'POST', 
  credentials: 'same-origin',
  headers: {
      'Content-Type': 'application/json',
  },
 // Body data type must match "Content-Type" header        
  body: JSON.stringify(data), 
});
try {
    const newData = await response.json();
    console.log(`This is the new Data ${newData.temperature}`);
    return newData;
}catch(error){
  console.log("error", error);
}}

這是 updateUI()

const updateUI = async () => {
const request = await fetch('/getweather');
try{
  const allData = await request.json();
  console.log('Get request');
        document.getElementById('date').innerHTML = allData.date;
        document.getElementById('temp').innerHTML = allData.temperature;
        document.getElementById('content').innerHTML = allData.userResponse;
}catch(error){
  console.log("error", error);
}}

發生的情況是 UI 首先更新,因此它第一次獲得 undefined 的值,當我重新加載頁面並輸入新數據時,UI 將使用上次的數據進行更新。

您需要返回從 postData 返回的postData

getWeather(baseURL, ZIP, key,).then((data) => {
   return postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings })
}).then(() => {
   return updateUI()
})

你可以這樣寫的另一種方式是這樣的:

async function run() {
   await getWeather(baseURL, ZIP, key)
   await postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings })
   await updateUI()
}

您的postData()也是異步 function。 因此,您也必須等待:

getWeather(baseURL, ZIP, key,).then(async (data) => {
    await postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings })
}).then(
    updateUI()
)}

我有一段時間沒有做過 javascript,但我想這樣更清楚:

const performAction = async (e) => {
const ZIP = document.getElementById('zip').value;
const fellings = document.getElementById('feelings').value;
console.log(`${baseURL}${ZIP},us&appid=${key}`);
try{
const data = await getWeather(baseURL, ZIP, key,);
const postData= await postData('/addweather', {temperature: data.main.temp ,date:newDate, userResponse: fellings });
} catch(e) {
console.log(e)
} finally {
    updateUI();
}

此外,您不必等待 json 的解析,並且 try catch 應該包含您的請求:

const postData = async ( url = '', data = {}) => {
console.log(`This is what we fetch ${data.temperature}`);
console.log(`This is what we fetch ${data.date}`);
console.log(`This is what we fetch ${data.userResponse}`);
try {
  const response = await fetch(url, {
  method: 'POST', 
  credentials: 'same-origin',
  headers: {
      'Content-Type': 'application/json',
  },
 // Body data type must match "Content-Type" header        
  body: JSON.stringify(data), 
});

    const newData = response.json();
    console.log(`This is the new Data ${newData.temperature}`);
    return newData;
}catch(error){
  console.log("error", error);
}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM