0

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.

2
  • if you didn't have the callback then the function would immediately invoke your function when you call download() rather than waiting 3 seconds to call it. The callback here doesn't represent the start of the download process, but rather the end of it. So once the download which takes x amount of time completes, your callback would get called. Here setTimeout is being used to mimic the download process which takes x amount of time. The code inside the callback would then have access to the data retrieved from performing the download, such as the downloaded content Commented Mar 22, 2020 at 0:16
  • Thank you for your response but: the console.log is called after 3 sec, why wouldn't a normal method (instead callback) be called after 3 sec then? Commented Mar 22, 2020 at 8:37

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.