Skip to content

Instantly share code, notes, and snippets.

@ajchambeaud
Created April 24, 2017 23:30
Show Gist options
  • Save ajchambeaud/cc8c36f46685d253e37385da056eed81 to your computer and use it in GitHub Desktop.
Save ajchambeaud/cc8c36f46685d253e37385da056eed81 to your computer and use it in GitHub Desktop.
Promisify node CPS functions
/*
* Simple async function: Dividir dos numeros. Falla si el deniminador es cero
*/
function ioDivisionOpeation(x, y, callback) {
setTimeout(
() => {
if (y === 0) {
return callback(new Error('Division by cero'));
}
callback(null, x / y);
},
3000
);
}
/*
* Wrappea la version CPS retornando una Promise de ES6
*/
function ioDivisionPromisified(x, y) {
// Retorna un nuevo objeto promise
return new Promise((resolve, reject) => {
// Invocamos a la funcion original pasandole el callback como lo requiere
ioDivisionOpeation(x, y, (error, result) => {
if (error) {
// Si ocurre un error llamamos a reject (con early return)
return reject(error);
}
// Si esta todo bien llamamos a resolve pasando el resultado
resolve(result);
});
});
}
/*
* Uso de la version promisificada (?)
*/
ioDivisionPromisified(10, 2)
.then(result => {
console.log('result: ', result);
})
.catch(error => {
console.log('Fail: ', error);
});
/*
* Los errores se capturan en el metodo catch
*/
ioDivisionPromisified(10, 0)
.then(result => {
console.log('result: ', result);
})
.catch(error => {
console.log('Fail: ', error);
});
/*
* Promise chaining (encadenamiento de promesas)
*/
ioDivisionPromisified(4, 2)
.then(result => {
// El metodo then SIEMPRE retorna una promesa
// Si retornamos un valor, este se pasa como parametro en el callback del siguiente llamado a then
return `result: ${result}`;
})
.then(message => {
console.log(message);
})
.then(() => {
// Si no retirnamos un valor, el callback del siguiente llamado a then no recibe parametros
console.log('All done!');
})
.catch(error => {
console.log('Fail: ', error);
});
/*
* Podemos encadenar llamados a operaciones async usando Promise chaining
*/
ioDivisionPromisified(100, 2)
.then(result => ioDivisionPromisified(result, 2))
.then(result => ioDivisionPromisified(result, 2))
.then(result => ioDivisionPromisified(result, 2))
.then(result => {
console.log(`Final result: ${result}`);
})
.catch(error => {
console.log('Fail: ', error);
});
/*
* Si alguna de las operaciones falla, es capturada en el ultimo catch
*/
ioDivisionPromisified(100, 2)
.then(result => ioDivisionPromisified(result, 2))
.then(result => ioDivisionPromisified(result, 0))
.then(result => ioDivisionPromisified(result, 2))
.then(result => {
console.log(`Final result: ${result}`);
})
.catch(error => {
console.log('Final Fail: ', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment