skip to Main Content

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


  1. The reason it is undefined is because the return value of console.log() is undefined. Removing it allows out to be referenced:

    let url = 'https://ac7minh6n7s3rw4qfchrofbwai0amiko.lambda-url.eu-north-1.on.aws/';
    
    fetch(url)
    .then(res => res.json())
    .then(out => document.write('JSON string: ', JSON.stringify(out)))
    .catch(err => { throw err });
    
    Login or Signup to reply.
  2. 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 before then is called.

    .then(out => console.log('JSON: ', out))
    

    The return value of console.log is undefined so you are passing undefined into the function which tried to document.write the value.

    You need to return the value you want to handle:

    .then(out => {
        console.log('JSON: ', out);
        return out;
    })
    

    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:

    .then(out => {
        console.log('JSON: ', out);
        document.write('JSON string: ', JSON.stringify(out);
        return out;
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search