fetch()调用不返回任何数据 [英] fetch() call not returning any data
问题描述
我的fetch()调用有问题,无法正常工作.我有一个在此函数中调用自身的递归方法,但是一旦它传递了if语句,则数据本身不会被解析为下面的.then()调用.我想将递归方法保留在此函数内.因为此函数正在调用的系统会将data.result更改为另一个不为null的结果.我只是不知道什么时候会发生,所以这就是为什么我使用递归方法.
I'm having a problem with my fetch() call not working correctly. I have a recursion method that calls itself within this function, but once it passes the if statement, the data itself is not being resolved to the .then() call below. I would like to keep the recursion method within this function. Because the system that this function is calling will change the data.result to a different result that is not null. I just don't know when that will happen, hence that is why I'm using the recursion method.
var someToken = "actually token";
function getResult(getToken) {
return new Promise((resolve, reject) => {
fetch(url, {
headers: {
"Authorization": something,
"Jenkins-Crumb": getToken
},
redirect: 'follow',
}).then(response => {
return response.json()
}).then(data => {
if (data.result == null) {
console.log('retrieving data')
getResult(getToken)
} else if (data.result == "SUCCESS") {
console.log('success')
resolve(data)
}
}).catch(err => {
reject(err)
})
})
}
getResult(someToken).then(data => {
console.log(data)
}).catch(err => console.log(err))
推荐答案
尝试使用 async ... await
,您的代码会简单得多
try using async...await
and your code will be much simpler
var someToken = "actually token";
async function getResult(getToken) {
const resp = await fetch(url, {
headers: {
"Authorization": something,
"Jenkins-Crumb": getToken
},
redirect: 'follow',
});
const data = await resp.json();
if (data.result == null) {
console.log('retrieving data')
return getResult(getToken)
} else if (data.result == "SUCCESS") {
console.log('success')
return data;
}
}
getResult(someToken).then(data => {
console.log(data)
}).catch(err => console.log(err))
这篇关于fetch()调用不返回任何数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!