JavaScript中未返回来自catch的错误



我创建了下一个函数,如果存在,它应该返回responsedataerror

const login = function(cb) {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => {
cb(null, null, response);
return response.json();
})
.then((data) => {
cb(data, null, null);
})
.catch((e) => {
console.log('error inside catch:', e.message)
cb(null, null, e)
})
}
console.log(login((data, response, err) => console.log('data', data, 'response', response, 'error', err)))

所以,我必须返回所有这些值,但我只能返回data。如果我将this:https://jsonplaceholder.typicode.com/todos/1更改为this:https://j123sonplaceholder.typicode.com/todos/1,则返回err,得到undefined。回应也存在同样的问题
问题:如何获取所有这些值?

// you write
cb(response);
cb(data);
cb(error);
// so the data and error below make no sense
cb(response, data, error)

console.log中使用cb时,您向它传递了3个参数。但是在login函数声明中,cb只接受1个参数
这意味着您的console.log总是打印两次,第一次是API调用的响应,第二次是数据(如果成功-然后)或错误(如果失败-捕获)

const arr = []
const login = function (cb) {
// const arr = []; move array inside login function if not use outside
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => {
arr[0] = response;
return response.json();
})
.then((data) => {
arr[1] = data;
})
.catch((e) => {
arr[2] = e;
})
.finally(() => {
cb(...arr);
});
};
login((response, data, err) => console.log('response', response, 'data', data, 'error', err))
// console.log(arr[0]) // response
// console.log(arr[1]) // data
// console.log(arr[2]) // error

最新更新