gpt4 book ai didi

javascript - 如何从 Promise 获取 JSON

转载 作者:行者123 更新时间:2023-12-01 01:47:46 26 4
gpt4 key购买 nike

代码:

fetch(`https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=++++++++++&tags=obama&format=json&extras=url_m&nojsoncallback=true`, {
method: "GET",
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(response => {
console.log(response.json())
})

输出:

Promise {_40: 0, _65: 0, _55: null, _72: null}

最佳答案

然后添加另一个:

fetch(...).then(resp => resp.json()).then(data => ...)

请注意,如果您希望它拒绝 Promise,例如,fetch 只会在网络错误时出错。 500 响应,您必须检查状态代码并抛出:

fetch(url)
.then(resp => {
// you'll need to supply the function that checks the status here
if (http_response_ok(resp.status)) {
return resp.json();
} else {
throw new Error(`Got back ${resp.status}`);
}
}).then(data => {
// happy path
}).catch(err => {
// sad path
});

关于javascript - 如何从 Promise 获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com