0

I'm trying to get better at NodeJS, but I'm kinda confused about how to return functions properly. That's what I have:

var express = require('express');
const fetch = require('node-fetch');

const url = 'https://api.github.com/users/github';

function getjsonname(link) {
    fetch(link)
        .then(res => res.json())
        .then(json => {
            console.log(json.name + ' log inside function works'); // It returns "github log inside function works" properly
            return json.name; // This is how I'm trying to return, which should work like the log above
    }).catch(err => console.error(err));
}

console.log(getjsonname(url)); // It only returns "undefined"

Mostly topics say it's because async, callback or I\O, but I don't understand why it works in the log inside and not in the outside. The concept is kinda confusing for me yet.

  • The log inside fires when the getjsonname is actually complete, your last console.log fires before your .fetch code has finished. That's what async is. Your code is not running in a linear fashion like you expect. getjsonname is something that will finish in the future, your final console.log doesn't wait for it to finish before showing the output, it's merely returning the value of undefined as getjsonname has returned without completing the inner code yet – TommyBs Oct 05 '21 at 13:48
  • A good way to get your head round this is to think of putting your clothes in a washing machine. You can do other things whilst the washing machine is on, you don't stand there waiting for it to finish before moving onto a new task. At some point in the future your washing machine will "beep" to let you know it's done. This is what the callbacks are. They are code that runs when a job is complete. Try to do some more reading on async/await and promises – TommyBs Oct 05 '21 at 13:50

0 Answers0