M Yil
M Yil

Reputation: 957

Javascript - Callback vs Calling function from within another function

I have the following code:

function download(url, callback) {
    setTimeout(() => {
      // script to download the picture here
      console.log(`Downloading ${url} ...`);

      callback();

   }, 3* 1000);
}


download(url);

Why do I need to have a callback function. Can't I just create another function and call that function from within the download function? I don't see the point people saying that callbacks are needed for async programming.

Upvotes: 0

Views: 45

Answers (1)

buttface64
buttface64

Reputation: 143

Callbacks are necessary when a value depends on the response of a promise. Often when we request data from other sources, such as an external API, we don’t always know when our data will be served back.

I think what your example is alluding to would be something like this:

function download(url, callback) {
    console.log(`Downloading ${url} ...`);
    fetch(url)
      .then((response) => {
          callback(null, response)
      })
      .catch((error) => {
         callback(err, null)
      });
}

download("http://example.com/movies.json", function(err, response){
    // Do something with the response data
});

Can't I just create another function and call that function from within the download function?

It would make more sense to pass your other function as the callback, like so:

function handleMovieData(err, response) {
    // Do something with the response data
}

download("http://example.com/movies.json", handleMovieData);

Nick Parsons' comment explains this well


EDIT: Alternatively to passing in a callback function, you could utilize async/await (untested)

async function download(url) {
    console.log(`Downloading ${url} ...`);
    return new Promise(function(resolve, reject) {
      fetch(url)
        .then((response) => {
            resolve(response)
        })
        .catch((error) => {
            reject(err)
        });
    })
}

const movieData = await download("http://example.com/movies.json");

handleMovieData(movieData);

Upvotes: 1

Related Questions