簡體   English   中英

JavaScript,異步等待返回 promise 而不是結果

[英]JavaScript, async await is returning a promise instead of the result

我有以下 function。 為什么我在調用GetProfile("username")時會收到Promise { <state>: "pending" } 我應該怎么辦?

const GetProfile = async (username) => {
  await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => {
    console.log(resp.json());
  });
};

resp.json()返回一個Promise這就是你在控制台記錄的內容。 它應該在獲取實際數據之前解決。 由於您處於async function 中,因此您可以執行以下操作。 請注意,沒有必要擁有這個then阻止你擁有。

const GetProfile = async (username) => {
  const res = await fetch(`${host}/api/v1/getprofile/${username}`);
  const data = await res.json();
  return data;
  });
};

這是 javascript 中的正常async function 行為,它們返回承諾。

在 React 中,您可以將值保存在 state 中。

const [profile,setProfile]=useState(null)

    useEffect(()=> {


        const GetProfile = async (username) => {
           const profile = await fetch(`${host}/api/v1/getprofile/${username}`).then(resp => resp.json());
           setProfile(profile)}

        GetProfile(username);

    },[username])

因為您在異步調用之后使用.then ,並且resp.json()還返回一個Promise ,您的 .then .then()調用沒有返回它。

您的情況是:

const response = await fetch(`${host}/api/v1/getprofile/${username}`)
return response.json();

並且因為json() function 本身是 Promise (它不是await 'ed),所以讀取json()調用是 'Pending' ZA5A3F0F287A448982AAC520CFFE47'

因此,要解決此問題,請嘗試:

await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => resp.json())

或者

const response = await fetch(`${host}/api/v1/getprofile/${username}`)

return await response.json();

默認情況下async function 總是返回 promise 您需要做的是使用await執行它,您可以提取結果,或者將其與then鏈接並繼續。

我用await做了一個例子:

const GetProfile = async (username) => {
  await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => {
    console.log(resp.json());

    return resp.json()
  });
};


const result = await GetProfile()
console.log(result);

筆記:
您需要從then之一返回resp.json()以查看結果。

暫無
暫無

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

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