I've been messing around with the fetch() api recently, and noticed something which was a bit quirky.
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => {
return {
data: response.json(),
status: response.status
}
})
.then(post => document.write(post.data));
;
post.data returns a Promise object.
http://jsbin.com/wofulo/2/edit?js,output
However if it is written as:
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => response.json())
.then(post => document.write(post.title));
;
post here is a standard Object which you can access the title attribute.
http://jsbin.com/wofulo/edit?js,output
So my question is: why does response.json return a promise in an object literal, but return the value if just returned?
Why does response.json return a promise?
Because you receive the response as soon as all headers have arrived. Calling .json() gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.
Why do I get the value if I return the promise from the then handler?
Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.
You can use
fetch(url).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
console.log(res.status, res.data.title)
}));
or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.
This difference is due to the behavior of Promises more than fetch() specifically.
When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post is provided by the Promise returned from response.json().
When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:
if the handler function:
returns a value, the promise returned by then gets resolved with the returned value as its value;
throws an error, the promise returned by then gets rejected with the thrown error as its value;
returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the
resolution/rejection of the promise returned by the handler. Also, the
value of the promise returned by then will be the same as the value of
the promise returned by the handler.
The json() method is available on all fetch() function. The json() method returns a Promise. Remember, when returning a Promise, it is still pending because it is asynchronous (assuming the data is not there yet). So to get the data AFTER using the json() method, you need to use another then() method so it will just return the data after it arrives.
To answer your question, It is what it is, its just the way of doing that.
Its like Promise ---> Another Promise ----> data
Use await with responce.json() also
const responce = await fetch(url);
const result = await responce.json();
Use await with responce.json() also
Related
I've been messing around with the fetch() api recently, and noticed something which was a bit quirky.
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => {
return {
data: response.json(),
status: response.status
}
})
.then(post => document.write(post.data));
;
post.data returns a Promise object.
http://jsbin.com/wofulo/2/edit?js,output
However if it is written as:
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => response.json())
.then(post => document.write(post.title));
;
post here is a standard Object which you can access the title attribute.
http://jsbin.com/wofulo/edit?js,output
So my question is: why does response.json return a promise in an object literal, but return the value if just returned?
Why does response.json return a promise?
Because you receive the response as soon as all headers have arrived. Calling .json() gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.
Why do I get the value if I return the promise from the then handler?
Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.
You can use
fetch(url).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
console.log(res.status, res.data.title)
}));
or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.
This difference is due to the behavior of Promises more than fetch() specifically.
When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post is provided by the Promise returned from response.json().
When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:
if the handler function:
returns a value, the promise returned by then gets resolved with the returned value as its value;
throws an error, the promise returned by then gets rejected with the thrown error as its value;
returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the
resolution/rejection of the promise returned by the handler. Also, the
value of the promise returned by then will be the same as the value of
the promise returned by the handler.
The json() method is available on all fetch() function. The json() method returns a Promise. Remember, when returning a Promise, it is still pending because it is asynchronous (assuming the data is not there yet). So to get the data AFTER using the json() method, you need to use another then() method so it will just return the data after it arrives.
To answer your question, It is what it is, its just the way of doing that.
Its like Promise ---> Another Promise ----> data
Use await with responce.json() also
const responce = await fetch(url);
const result = await responce.json();
Use await with responce.json() also
I've been messing around with the fetch() api recently, and noticed something which was a bit quirky.
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => {
return {
data: response.json(),
status: response.status
}
})
.then(post => document.write(post.data));
;
post.data returns a Promise object.
http://jsbin.com/wofulo/2/edit?js,output
However if it is written as:
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => response.json())
.then(post => document.write(post.title));
;
post here is a standard Object which you can access the title attribute.
http://jsbin.com/wofulo/edit?js,output
So my question is: why does response.json return a promise in an object literal, but return the value if just returned?
Why does response.json return a promise?
Because you receive the response as soon as all headers have arrived. Calling .json() gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.
Why do I get the value if I return the promise from the then handler?
Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.
You can use
fetch(url).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
console.log(res.status, res.data.title)
}));
or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.
This difference is due to the behavior of Promises more than fetch() specifically.
When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post is provided by the Promise returned from response.json().
When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:
if the handler function:
returns a value, the promise returned by then gets resolved with the returned value as its value;
throws an error, the promise returned by then gets rejected with the thrown error as its value;
returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the
resolution/rejection of the promise returned by the handler. Also, the
value of the promise returned by then will be the same as the value of
the promise returned by the handler.
The json() method is available on all fetch() function. The json() method returns a Promise. Remember, when returning a Promise, it is still pending because it is asynchronous (assuming the data is not there yet). So to get the data AFTER using the json() method, you need to use another then() method so it will just return the data after it arrives.
To answer your question, It is what it is, its just the way of doing that.
Its like Promise ---> Another Promise ----> data
Use await with responce.json() also
const responce = await fetch(url);
const result = await responce.json();
Use await with responce.json() also
I've been messing around with the fetch() api recently, and noticed something which was a bit quirky.
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => {
return {
data: response.json(),
status: response.status
}
})
.then(post => document.write(post.data));
;
post.data returns a Promise object.
http://jsbin.com/wofulo/2/edit?js,output
However if it is written as:
let url = "http://jsonplaceholder.typicode.com/posts/6";
let iterator = fetch(url);
iterator
.then(response => response.json())
.then(post => document.write(post.title));
;
post here is a standard Object which you can access the title attribute.
http://jsbin.com/wofulo/edit?js,output
So my question is: why does response.json return a promise in an object literal, but return the value if just returned?
Why does response.json return a promise?
Because you receive the response as soon as all headers have arrived. Calling .json() gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.
Why do I get the value if I return the promise from the then handler?
Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.
You can use
fetch(url).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
console.log(res.status, res.data.title)
}));
or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.
This difference is due to the behavior of Promises more than fetch() specifically.
When a .then() callback returns an additional Promise, the next .then() callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post is provided by the Promise returned from response.json().
When you return a plain Object, though, .then() considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post in this case is simply the Object you created, which holds a Promise in its data property. The wait for that promise to be fulfilled is still incomplete.
In addition to the above answers here is how you might handle a 500 series response from your api where you receive an error message encoded in json:
function callApi(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json().then(response => ({ response }));
}
return response.json().then(error => ({ error }));
})
;
}
let url = 'http://jsonplaceholder.typicode.com/posts/6';
const { response, error } = callApi(url);
if (response) {
// handle json decoded response
} else {
// handle json decoded 500 series response
}
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:
if the handler function:
returns a value, the promise returned by then gets resolved with the returned value as its value;
throws an error, the promise returned by then gets rejected with the thrown error as its value;
returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the
resolution/rejection of the promise returned by the handler. Also, the
value of the promise returned by then will be the same as the value of
the promise returned by the handler.
The json() method is available on all fetch() function. The json() method returns a Promise. Remember, when returning a Promise, it is still pending because it is asynchronous (assuming the data is not there yet). So to get the data AFTER using the json() method, you need to use another then() method so it will just return the data after it arrives.
To answer your question, It is what it is, its just the way of doing that.
Its like Promise ---> Another Promise ----> data
Use await with responce.json() also
const responce = await fetch(url);
const result = await responce.json();
Use await with responce.json() also
I am using fetch to get data but it keeps returning promise as pending. I've seen many posts regarding this issue and tried all the possibilities but didn't solve my issue. I wanted to know why the fetch returns promise as pending in brief what are the possible cases where fetch returns pending status?
My piece of code for reference:
fetch(res.url).then(function(u){
return u.json();
})
.then(function(j) {
console.log(j);
});
Promises are a way to allow callers do other work while waiting for result of the function.
See Promises and Using Promises on MDN:
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation completed successfully.
rejected: meaning that the operation failed.
The fetch(url) returns a Promise object. It allows attaching “listener” to it using .then(…) that can respond to result value (response to the request). The .then(…) returns again Promise object that will give result forward.
async and await
You can use JS syntax sugar for using Promises:
async function my_async_fn(url) {
let response = await fetch(url);
console.log(response); // Logs the response
return response;
)
console.log(my_async_fn(url)); // Returns Promise
async functions return a Promise. await keyword wraps rest of the function in .then(…). Here is equivalent without await and async:
// This function also returns Promise
function my_async_fn(url) {
return fetch(url).then(response => {
console.log(response); // Logs the response
return response;
});
)
console.log(my_async_fn(url)); // Returns Promise
Again see article on Promises on MDN.
As one of the upper comments said, fetch() is a promise that calls .then() when the request is handled by the network. The parameter in this callback is another promise that calls $.then() when we get the response from the server.
Maybe you should try something like this:
fetch(res.url)
.then(function(serverPromise){
serverPromise.json()
.then(function(j) {
console.log(j);
})
.catch(function(e){
console.log(e);
});
})
.catch(function(e){
console.log(e);
});
or in lambda notation:
fetch(res.url)
.then((serverPromise) =>
serverPromise.json()
.then((j) => console.log(j))
.catch((e) => console.log(e))
})
.catch((e) => console.log(e));
This is the first time I post here in StackOverflow, so please let me know if I made any mistake or you have any sugestions, thanks!
A fetch() is a network operation. To avoid hanging until we get a reply from the network, we defer it to the background and give ourselves the promise that it will complete eventually.
So fetch(url).then((data) => data.json()) means that we fetch the url, wait for data to come in, get the json representation of the data and wait for that too (data.json() is a promise too)
Until we get a result, the promise is in the pending state. The server hasn't replied to our request yet.
--
Reading the comments, it might be nice to add a error handler as that is why the current fetch is supposedly not doing anything:
fetch().then((data) => data.json()).catch((error) => console.log(error))
I have this code:
fetch(url).then(response => {
const json = response.json();
console.log('simplest possible fetch', json, json.where);
});
In the console I get:
simplest possible fetch Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} undefined
I get this most of the time. Sometimes I get the "success" status. To me this implies the callback is being run before the fetch promise has resolved.
I want the function to be run only when the fetch completes. How do I do this?
response.json() returns a promise, use then callback to get the data:
The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.
fetch(url)
.then(response => response.json())
.then(data => console.log('simplest possible fetch', data, data.where));