gpt4 book ai didi

javascript - Promise、fetch、codestyle。请解释 .then(checkStatus).then(parseJSON)

转载 作者:行者123 更新时间:2023-11-29 10:33:27 25 4
gpt4 key购买 nike

我有测试码!

function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText));
}
}
function parseJSON(response) {
return response.json()
}

我可以这样写:

function load(id) {
return fetch('/api/test/'+ id + '/', {method: 'get'})
.then(response => checkStatus(response))
.then(response => parseJSON(response))
.catch(error=>console.error(error))

或者我可以这样写:

function load(id) {
return fetch('/api/test/'+ id + '/', {method: 'get'})
.then(checkStatus)
.then(parseJSON)
.catch(error=>console.error(error))

请解释第二种变体。它是怎么做到的.then(checkStatus)
.then(parseJSON)
工作?
我只是写了对函数的引用,并没有运行它。

最佳答案

.then 将函数作为其参数...它调用传递单个参数的函数,该参数是 promise 的解析值

所以想到

return fetch('/api/test/'+ id + '/', {method: 'get'})
.then(checkStatus)

作为

return fetch('/api/test/'+ id + '/', {method: 'get'})
.then(function(resultOfPromise) {
return checkStatus(resultPromise);
})

By the way, this isn't limited to promise/then type code ... consider the following

function doThings(p1) {
console.log(p1);
return 'good bye';
}
setTimeout(doThings, 1000, "hello world");

same concept - except that the the value returned by the callback in setTimout is ignored. In .then() however, the value returned by the callback is used as the resolved value of a Promise ... which is basically how promise chaining works (this is an over simplified explanation)

关于javascript - Promise、fetch、codestyle。请解释 .then(checkStatus).then(parseJSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40910305/

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