Javascript. Promises, todo lo que necesitas saber (I)

Aprende los conceptos básicos sobre el objeto Promise para realizar tareas asíncronas en Javascript

El objeto Promise

const myFirstPromise = new Promise(function(resolve, reject) {
// do a task
});

Estado de una promise

Creando nuestra primera Promise

const myFirstPromise = new Promise(function(resolve, reject) {
setTimeout(() => resolve('finished'), 3000);
});
const myFirstPromise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error('failed')), 3000);
});

Consumiendo una Promise

Método then

const myFirstPromise = new Promise(function(resolve, reject) {
setTimeout(() => resolve('finished'), 3000);
});
myFirstPromise.then(
function(result) { console.log(result); },
function(error) { /* do something when rejected */}
);
// logs: "finished"

Método catch

const myFirstPromise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error('failed')), 3000);
});
myFirstPromise.catch(
function(error) { console.log(error.message); }
);
// logs: "failed"

Método finally

const myFirstPromise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error('failed')), 3000);
});
myFirstPromise.finally(
function() { console.log('promise finished'); }
);
// logs: "promise finished"
const myFirstPromise = new Promise(function(resolve, reject) {
setTimeout(() => resolve('finished'), 3000);
});
myFirstPromise
.finally(
function() { console.log('promise finished'); }
)
.then(
function(result) { console.log(result); } // "finished"
);

Promises y el Event Loop

const promise = new Promise(resolve => resolve('tercero'));
console.log('primero');
promise.then(result => console.log(result));
console.log('segundo');
// primero
// segundo
// tercero

Conclusiones

¿Quieres recibir más artículos como este?

Written by

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store