user1780413
user1780413

Reputation: 133

pattern if fail 1 try 2 if fail try 3 for nodejs

hello im finding a pattern for a specific job;

lets say im finding a title in a page with DOM

if there is found title then put it to var title if var title is still empty then try the next function if var title is still empty then try the next function

is there a better way then

// Find Title
output.title = $('title').text();

if (null(output.title)) {
    output.title = second try
};

if (null(output.title)) {
    output.title = 3rd try
};

etc ? 

Upvotes: 0

Views: 58

Answers (1)

Niall Paterson
Niall Paterson

Reputation: 3580

My version makes it much more scalable and logical. Use an array and a while loop (Using the async module):

var functions = [function1, function2, function3]
var i = 0
var output.title // to deal with scope issue of output.title only being defined inside whilst. Could have put output.title as argument for callback
async.whilst(
     function () { return i < functions.length && !output.title },
     function (callback) {
          output.title = functions[i]
          i++
          callback()
}, function () {
     if (output.title) {
         //have title
     }
     else {
         // no title was found
     }
})

Upvotes: 1

Related Questions