反应等待承诺解决未获取数据

时间:2021-04-21 14:12:36

标签: javascript reactjs async-await promise

我在以下函数中使用了 async/await

forgotPassword = async ({ variables }) => {
    console.log(variables)
    const url = `//url constructed`
    console.log(url)
    try {
      const result: any = await fetch(url, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          mode: 'no-cors'
        }
      })

      console.log('result fetched is -->', result)

      return {
        data: {
          login: result.json()
        }
      }
    } catch (err) {
      this.setState({
        error:
          err?.response?.data?.error_description || err.message || strings.genericError
      })
      throw err
    }
  }

所以,在我这样做的结果中

result.json()

我收到如下回复:

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
Status: "Successful"
Time: "1619013232787"
__proto__: Object

所以当我尝试做

const status = result?.Status

然后它给了我undefined

如何得到响应?连承诺都兑现了。

1 个答案:

答案 0 :(得分:4)

您需要等待 result.json() 因为它返回一个承诺。 https://developer.mozilla.org/de/docs/Web/API/Body/json

 try {
      const result: any = await fetch(url, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          mode: 'no-cors'
        }
      })
      const data = await result.json();
      return {data};