Reputation: 4200
I created the next function that should return the response
, data
and error
in case if exists.
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)))
So, I have to return all these values, but I can return just data
. If I change this: https://jsonplaceholder.typicode.com/todos/1
to this: https://j123sonplaceholder.typicode.com/todos/1
, to return err
, I get undefined
. The same issue is with response.
Question: How to get all these values?
Upvotes: 0
Views: 96
Reputation: 1034
// you write
cb(response);
cb(data);
cb(error);
// so the data and error below make no sense
cb(response, data, error)
You passed 3 params to the cb
when using it in console.log
. But in the login
function declaration, cb
accepts only 1 param.
That means your console.log
always prints 2 times, the first is the Response of API call and the second is the data (if success - then) or error (if fail - catch).
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
Upvotes: 3