JS 获取 API 访问返回值



这是我从获取调用访问结果的方式:

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);
}();

这里有一些很好的获取资源和一个示例。

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://developer.mozilla.org/en-US/docs/Web/API/Body/text https://developer.mozilla.org/en-US/docs/Web/API/Body/json

您可能还想熟悉承诺。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise


function doSomethingWithText(text) {
console.log('The text is:', text);
}
fetch('someUrl.html')
.then(data => data.text())
.then(doSomethingWithText)
.catch(error => new Error(error));

fetch 方法返回解析为响应对象的承诺。

收到回复后,由您决定如何处理它。可以在响应正文上使用方法(如 json、文本或 blob(将数据转换为要使用的所需格式。

最新更新