簡體   English   中英

努力用異步等待來包裝承諾

[英]struggle to wrap promise with async await

我得到了意外的標識符,但不確定是什么錯誤。 我正在使用fetch,這已經是一個承諾。

async getUsers = () => {
  const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())

  return resp
}

getUsers().then(users => console.log(users))

請注意async關鍵字的位置:

不:

async getUsers = () => {

但:

getUsers = async () => {

跑:

 getUsers = async () => { const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => response.json()) return resp; }; getUsers().then(users => console.log(users)) 

根據評論:

我應該將then()getUsers()嗎? async / await應該消除then()我對嗎?

是的,您可以await任何Promise 或有時同時使用.then()await其他人(如上面的代碼一樣)。 但是您也可以使用async / await

下面的示例不使用.then()

 getUsers = async () => { const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1') return resp.json(); }; (async () => { // notice to use the await keyword, the code must be wrapped in an async function const users = await getUsers(); console.log(users); })(); 

除了@acdcjunior指出的異步單詞中的錯字外,您還將async / await與通常的promise處理( .then() )混合在一起.then()這沒錯,但有點敗筆。 僅使用async / await看起來像:

 const getUsers = async () => { const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1'); return resp.json(); } async function fetchUsers() { try { const users = await getUsers(); console.log(users); } catch(err) { console.log(err); } } fetchUsers(); 

您的語法錯誤:

const getusers = async () => {
  ...
}

const是可選的

您聲明函數的語法是錯誤的,這里有一些解釋。

如果getUsersgetUsers組件類的方法,則語法應為:

  getUsers = async () => {
    const resp = await fetch(
      'https://jsonplaceholder.typicode.com/posts/1'
    ).then(response => response.json());
    return resp;
  };

要么 :

  async getUsers() {
    const resp = await fetch(
      'https://jsonplaceholder.typicode.com/posts/1'
    ).then(response => response.json());
    return resp;
  };

如果它在react組件類之外或在無狀態箭頭函數組件中,則可以使用以下語法:

  const getUsers = async () => {
    const resp = await fetch(
      'https://jsonplaceholder.typicode.com/posts/1'
    ).then(response => response.json());
    return resp;
  };

 const getUsers = async () => { try { const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1'); return resp.json(); } catch(e) { console.error(e) } } (async () => { const users = await getUsers(); console.log(users) })() 

使用它,然后運行

暫無
暫無

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

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