javascript - JS Fetch API 访问返回值
问题描述
这就是我从 fetch 调用中访问结果的方式:
let data;
fetch(someUri)
.then((response) => response.json())
.then(_data => {
data = _data;
})
.catch(error => {
console.error(error);
});
是否也可以从 fetch 函数本身访问结果,如下所示:
let data = fetch(someUri)
.then((response) => response.json())
.then(data => {
// do some stuff
return data;
})
.catch(error => {
return error;
});
data
JSON数据或错误也是如此。我在 Chrome 控制台中看到结果在变量中,但我不知道如何访问它,因为它包含其他信息。
解决方案
您可以将其包装在立即调用的异步函数中并使用 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);
}();
推荐阅读
- javascript - 如何在“Google Chrome 控制台内部”循环延迟 1 秒
- python - 是否可以直接使用类型提示验证?
- c# - 我的代码有什么问题吗,因为它在数据库中保存了相同的数据,即使扫描了不同的指纹?
- python - Django 从 postgresql 数据库填充的下拉菜单的完整示例
- vb.net - 无法关闭我的 MS Access 数据库的 OleDbDataReader
- angularjs - 如何使用角度获取从输入类型文件到 img src 的图像路径
- .htaccess - 当我打开像 www.domain.com 这样的域时,它会重定向到 www.www.domain.com
- python - 复制然后粘贴在python终端mac中产生垃圾
- javascript - 从表中获取数据以显示为纯文本
- php - 有没有办法连接 1 行唯一键并在表单中显示其数据?