Skip to content

parallel args

Kory Nunn edited this page Jun 23, 2017 · 1 revision

Get two random numbers asynchronously, in parallel, and then add them as soon as they are both available.

Promises:

function getRandomValue(){
    return new Promise(function(resolve){
        setTimeout(function(){
            return resolve(parseInt(Math.random() * 10));
        }, Math.random() * 100);
    });
}

function add(a, b){
    return a + b;
}

var value1 = getRandomValue();
var value2 = getRandomValue();
var result = Promise.all([value1, value2])
    .then(function(items){
        return add(items[0], items[1]);
    });

result
    .then(result => console.log(result))
    .catch(error => console.log(error));

Righto:

function getRandomValue(callback){
    setTimeout(function(){
        callback(null, parseInt(Math.random() * 10));
    }, Math.random() * 100);
}

function add(a, b){
    return a + b;
}

var value1 = righto(getRandomValue);
var value2 = righto(getRandomValue);
var result = righto.sync(add, value1, value2);

result((error, result) => console.log(error, result));
Clone this wiki locally