1

Basically, I want to pit two asynchronous calls against each other, and only use the winner.

I cannot seem to figure out how to do this, only how to prevent it. Is it remotely possible?

Lame pseudo-code:

//rigging a race
function MysqlUser()
{
        setTimeout(function(){
                return "mysqluser";
        }, 500);
}

function ADUser()
{
        setTimeout(function(){
                return "aduser";
        }, 1000);
}

function getUser()
{
        var user = null;
        user = ADBind();
        user = MysqlBind();
        //if user != null
        return user;
        //else?
}

I'd like (in this instance) for MysqlUser to win out over ADUser.

Any help would be appreciated.

kbertrand
  • 33
  • 1
  • 6

1 Answers1

1

You can write a simple first function that takes a list of task and calls back with the result of only the first to complete:

function first(tasks, cb) {
    var done = false;
    tasks.forEach(function(task) {
        task(function(result) {
            if(done) return;
            done = true;
            cb(result);
        });                   
    });
}

Then:

function mysqlUser(cb) {
        setTimeout(function() {
                cb("mysqluser");
        }, 500);
}

function adUser(cb) {
        setTimeout(function() {
                cb("aduser");
        }, 1000);
}


first([mysqlUser, adUser], function(user) {
    console.log(user);
});

This might need some more thought if you want to cope with both operations failing.

Eric
  • 95,302
  • 53
  • 242
  • 374