0

I was wondering wich of the following is the right thing to do, or which one is faster?

I have a function which generates a HTML string and gives it back.

How should I return this string that I generate, with a callback or just return it?

MyApp.prototype.makeChatMsg = function(message, callback) {

   var html = '<div class="media">';
   html += '<div class="media-body">';
   //html += '<h4 class="media-heading">' + message.user.first_name + ' ' + message.user.last_name + '</h4>';
   html += '<p>' + message.content + '</p>';
   html += '</div>';
   html += '</div>';

   callback(html); // see here
} 

vs

MyApp.prototype.makeChatMsg = function(message) {

   var html = '<div class="media">';
   html += '<div class="media-body">';
   //html += '<h4 class="media-heading">' + message.user.first_name + ' ' + message.user.last_name + '</h4>';
   html += '<p>' + message.content + '</p>';
   html += '</div>';
   html += '</div>';

   return html; // see here
}

Im using these functions like this within MyApp scope

First method

this.makeChatMsg(incomingMessage, function(html) {
    $('#messages').append(html); 
));

Second method

var newMessage = this.makeChatMsg(incomingMessage);
$('#messages').append(newMessage);

Generating a HTML string is this a asynchronous task or not? Im just not sure..

1
  • 1
    As it's not async, I would just return it. Commented Aug 2, 2014 at 13:49

2 Answers 2

2

Generally we should return from a function and avoid callbacks.

What I think callback is meant for when you have to use non-blocking or asynchronous call like an AJAX request. There every thing would be done with a callback

Because there you don't know when your task will be finished, so if you want to perform something after finishing that task, we use callback.

I'd say return is better that callback. If there are too many callbacks they result out as callback pyramid.

Sign up to request clarification or add additional context in comments.

2 Comments

is there a performance issue if I keep using those callbacks, does it create a new thread or something?
@webmaster I don't think there is a performance issue, in javascript there is nothing called as thread.
1

Go with the simpler solution, returning the string, until you have a reason to do something more complicated.

From what I can see, makeChatMsg will run extremely quickly. No reason for it to run asynchronously.

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.