The context is this: I have a 'toy' node.js server that returns the following json: { "message" : "hello there" } And this is returned if you do a GET request to "http://localhost:3060/" So, very simple.
Here is my 'baseline' code, featuring multiple .then(..) clauses
3 function footgun() { 4 fetch('http://localhost:3060/') 5 .then(res => res.json()) 6 .then(json => json.message) 7 .then(msg => console.log(msg)); The output is: hello there
Excellent. Very good. That's what I wanted.
I have been reading about how promises are implemented.
And so I know that each .then() returns a Promise object. But isn't that wasteful ?
Surely it would be more efficient to pack everything into one .then() clause ? Like this:
3 function footgun() { 4 fetch('http://localhost:3060/') 5 .then(res => { 6 const json = res.json(); 7 const msg = json.message; 8 console.log(msg); 9 }); The output is: undefined
That's the problem. Why is the result 'undefined' ? Why does this not work inside a single .then(..) clause ?
Thanks to anyone that volunteers an explanation or suggestion. :-) Gene Keto
then?.then()onres.json(). It's also about when to use.then()and when not to as the OP shows something like this too.then(json => json.message)which is superfluous so this questions is about MORE than just what those other links are discussing. See the answer below for a complete answer that covers all the issues in the OP's post, not just some of them. No need to dup a question that isn't fully answered by the dups.