I would like to print out data in my html from the link, but it always says "undefined" and I dont know, where is the problem. Can anyone help, please?
let url = 'https://ac7minh6n7s3rw4qfchrofbwai0amiko.lambda-url.eu-north-1.on.aws/';
fetch(url)
.then(res => res.json())
.then(out => console.log('JSON: ', out))
.then(out => document.write('JSON string: ', JSON.stringify(out)))
.catch(err => { throw err })
2
Answers
The reason it is
undefined
is because the return value ofconsole.log()
isundefined
. Removing it allows out to be referenced:The value passed to the
then
callback is the return value of the previous link in the chain. If that value is a promise, it is resolved beforethen
is called.The return value of
console.log
isundefined
so you are passingundefined
into the function which tried todocument.write
the value.You need to return the value you want to handle:
However since you aren’t creating a new promise, there’s really no need to use an extra
then
. You can just merge the two: