Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

express - Javascript: what is a callback?

In this article which I was referred to the following statement is made:

Callbacks are a way to make sure certain code doesn’t execute until other code has already finished execution.

The article then goes on to illustrate this with an example:

function doHomework(subject, callback) {
  alert(`Starting my ${subject} homework.`);
  callback();
}

doHomework('math', function() {
  alert('Finished my homework');

After this the articles states:

As you’ll see, if you type the above code into your console you will get two alerts back to back: Your ‘starting homework’ alert, followed by your ‘finished homework’ alert.

The implication seems to be that by using a callback the desired order of code execution has been ensured. That is you start your homework before you finish it. However, I feel I may have misunderstood the whole point of the article and therefore still do not understand callbacks and asynchronous code because when I slow down the first part of the doHomework function using setTimeout() the code executes (or at least returns) in the opposite order:

function doHomework(subject, callback) {

  setTimeout(function(){
      console.log(`Starting my ${subject} homework.`);
  }, 500); 

  callback();
}

doHomework('math', function() {
  console.log('Finished my homework');
});

The result I get from that is:

steve@Dell ~/my-app $ node app.js 
Finished my homework
Starting my math homework.
});

I am using node here (hence console.log() replaces alert()) but I do not think that is relevant.

It seems to me I have missed something quite fundamental and need to try and access what it is that I am trying to understand before I then try and understand it.

Any assistance on this journey would be greatly appreciated.

After getting great feedback I think the homework analogy was not helpful so I am now using the first code example in the article I referenced. The article gives this code:

function first(){
  // Simulate a code delay
  setTimeout( function(){
    console.log(1);
  }, 500 );
}

function second(){
  console.log(2);
}

first();
second();

The above returns 2 then 1 in the console.

I tried (without success) to reverse the return order to 1 then 2 with this:

function first(callback){
    setTimeout(function(){
        console.log(1);
    }, 500);
    callback();
}
function second(){
    console.log(2);
}
first(second);

The answer I got from Cleared (before it was edited) was to put the callback() inside the setTimeout() function. He used the homework example but here it is with this example:

function first(callback){
    setTimeout(function(){
        console.log(1);
        callback();
    }, 500);
}

function second(){
    console.log(2);
}

first(second);

I think that is closer to what I am imagining the article was getting at. It seems to make sense although I guess the precise context of what you are doing and what you want to happen determine what is right or wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general, the call to the callback is not at the end of the function, but rather after you have done the important things.

So if I understand your question, the doHomework-function should start doing homework (which takes time, in this case 500ms), and then the homework is finished. So the important things in your case is the console.log('Starting my ${subject} homework.'); which "takes 500ms" (since this is the time you need to do the homework).

Therefore, you should put the call to the callback right after console.log('Starting my ${subject} homework.');, i.e.

function doHomework(subject, callback) {

  setTimeout(function(){
      console.log(`Starting my ${subject} homework.`);
      callback();
  }, 500); 
}

doHomework('math', function() {
  console.log('Finished my homework');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...