简体   繁体   English

Javascript - 回调与从另一个函数中调用函数

[英]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.我不明白人们说异步编程需要回调的意义。

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.通常,当我们从其他来源(例如外部 API)请求数据时,我们并不总是知道何时会返回我们的数据。

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/await (未经测试)

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM