反应等待承诺解决不获取数据
React await promise resolve not getting data
我在以下函数中使用 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
如何获得响应?连诺言都兑现了
您需要等待 result.json(),因为它 returns 是一个承诺。 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};
我在以下函数中使用 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
如何获得响应?连诺言都兑现了
您需要等待 result.json(),因为它 returns 是一个承诺。 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};