【问题标题】:JavaScript, async await is returning a promise instead of the result异步等待在反应中返回承诺
【发布时间】:2022-01-09 20:49:42
【问题描述】:

功能

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

为什么我在调用像这样GetProfile("username");这样的函数时得到Promise { <state>: "pending" }

我该怎么办? 提前致谢!

【问题讨论】:

  • 因为 .json() 再次返回一个承诺,你必须等待或然后打印解决的结果
  • 解决办法是什么?
  • 这能回答你的问题吗? Trying to implement a SIMPLE promise in Reactjs
  • Promise.then() 返回承诺,async function 也返回承诺。没有办法在 javascript 中全局且完全地解决 promise。

标签: reactjs frontend fetch fetch-api


【解决方案1】:

既然你在一个async 函数中,一个干净的方法是:

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

【讨论】:

    【解决方案2】:

    这是 javascript 中的正常 async 函数行为,它们返回承诺。

    在 React 中,您可以将值保持在状态中。

    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])
    

    【讨论】:

      【解决方案3】:

      默认asyncfunction always returns 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);
      

      注意:
      您需要从thens 之一返回resp.json() 才能看到结果。

      【讨论】:

        【解决方案4】:

        因为您在异步调用之后使用了.then,并且resp.json() 还返回了Promise,而您的.then() 调用并未返回该.then()

        你的情况是:

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

        因为 json() 函数本身就是一个 Promise(不是 await'ed),所以读取 json() 调用就是你得到的“待处理” Promise。

        所以要解决这个问题,请尝试:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-03-20
          • 1970-01-01
          • 2019-10-20
          • 2019-07-20
          • 2017-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多