JS Fetch API访问返回值 [英] JS Fetch API access return value
本文介绍了JS Fetch API访问返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我从提取调用中访问结果的方式:
This is how I access the result from a fetch call:
let data;
fetch(someUri)
.then((response) => response.json())
.then(_data => {
data = _data;
})
.catch(error => {
console.error(error);
});
是否还可以从fetch函数本身访问结果,如下所示:
Is it also possible to access the result from the fetch function itself, like this:
let data = fetch(someUri)
.then((response) => response.json())
.then(data => {
// do some stuff
return data;
})
.catch(error => {
return error;
});
因此 data
将是JSON数据或错误.我在Chrome控制台中看到结果在变量中,但是我不知道如何访问它,因为它与其他信息包装在一起.
So data
will be either the JSON data or the error. I see in my Chrome console that the result is in the variable, but I don't know how to access it because it's wrapped with other information.
推荐答案
您可以将其包装在立即调用的异步函数中并使用await:
You can wrap it inside an immediately invoked async function and use await:
https://jsfiddle.net/ibowankenobi/ok72rfp6/
!async function(){
let data = await fetch("https://raw.githubusercontent.com/IbrahimTanyalcin/LEXICON/master/lexiconLogo.png")
.then((response) => response.blob())
.then(data => {
return data;
})
.catch(error => {
console.error(error);
});
console.log(data);
}();
这篇关于JS Fetch API访问返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文