簡體   English   中英

從異步函數返回解析值

[英]Return resolve-value from async function

在項目中,我使用的承諾(下面的代碼),它是如何可能,這一承諾仍然pending ,當我用關鍵字await 有人可以幫我弄清楚我在做什么錯嗎?

 const getTs = async () => { const response = await axios.get('...') .then(res => res.data) .catch(() => 'ERROR'); return response; }; console.log(getTs()); // Promise { <pending> } 

await只會停止async function主體的執行,而不會停止其他任何事情。 調用者未被阻止,代碼仍然是異步的,您將獲得一個諾言。 如果要記錄結果,則必須等待。

const getTs = () => axios.get('...').then(res => res.data).catch(() => 'ERROR');

getTs().then(console.log);
//     ^^^^^

要么

async function getTs() {
  try {
    const res = await axios.get('...');
    return res.data;
  } catch (e) {
    return 'ERROR';
  }
}

async function main() {
  const response = await getTs();
//                 ^^^^^
  console.log(response)
}
main();

一旦請求得到解決, getTs將被解決。 因此,您必須等待響應:

const getTs = async () => {
  const response = await axios.get('...')
    .then(res => res.data)
    .catch(() => 'ERROR');

  return response;
};

getTs().then(response => console.log(response));

暫無
暫無

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

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