Skip to content

Instantly share code, notes, and snippets.

@iamdey
Last active October 2, 2018 17:35
Show Gist options
  • Save iamdey/a5c342c74c7f0403e360bec9c3dfbdd5 to your computer and use it in GitHub Desktop.
Save iamdey/a5c342c74c7f0403e360bec9c3dfbdd5 to your computer and use it in GitHub Desktop.
Promise vs Async
// Disclaimer: Je n'ai pas testé le code qui va suivre
function eatAnAppleTheOldWay(apple, cb) {
setTimeout(function () {
var result = eat(apple);
cb(result);
}, 10);
}
function eatAnApple(apple) {
return new Promise((resolve, reject) => {
setTimeout(function () {
try {
var result = eat(apple);
resolve(result);
} catch (err) {
reject(err)
}
}, 10);
});
}
function exampleA() {
const operation = eatAnApple(new Apple());
operation.then((resultat) => {
console.log({ resultat });
});
}
// on peut enchainer les promesses!
function takeACoffee() {
throw new Error('no moar coffee');
}
function clearTheTable() {
return 'clear the table';
}
function exampleB() {
eatAnApple(new Apple())
.then(() => takeACoffee())
.then(() => clearTheTable())
.catch((err) => alert(`Huston on a un problème : ${err}`));
}
// Petite colle : décrire le comportement
function exampleC() {
const result = eatAnApple(new Apple())
.then(() => takeACoffee(), (err) => console.warn(err))
.then(() => clearTheTable())
.catch((err) => alert(`Huston on a un problème : ${err}`));
}
// -> correction
function exampleD() {
eatAnApple(new Apple())
.then(() => takeACoffee(), (err) => {
console.warn(err);
return Promise.reject(err);
})
.then(() => clearTheTable())
.catch((err) => alert(`Huston on a un problème : ${err}`));
}
// Pyramid of Doom
// Quand on a besoin des résultats
function exampleE() {
eatAnApple(new Apple())
.then((r1) => {
return takeACoffee(r1)
.then((r2) => {
return clearTheTable(r2)
.then((r3) => {
return { r1, r2, r3 };
});
});
})
.catch((err) => alert(`Huston on a un problème : ${err}`))
.then(pyramidResults => console.log({ pyramidResults }));
}
// async await
async function exampleF() {
try {
const r1 = await eatAnApple(new Apple());
const r2 = await takeACoffee(r1);
const r3 = await clearTheTable(r2);
return { r1, r2, r3 };
} catch (err) {
console.warn(err);
throw err;
}
}
// Plot twist
//
// une fonction async ça reste une promesse !
function exampleG() {
exampleF()
.then((results) => console.log('loul', { results }));
.catch(err => alert(err))
}
// Des fois, inutile de faire compliqué
async function exampleH() {
return await eatAnApple(new Apple());
}
// plus simplement:
function exampleI() {
return eatAnApple(new Apple());
]
// debugger pas à pas
// selon le stage de transpilation : ça peut utiliser yield directement ou un polyfill nécessitant l'api Promise
"use strict";
var exampleF = function () {
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
var r1, r2, r3;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return eatAnApple(new Apple());
case 3:
r1 = _context.sent;
_context.next = 6;
return takeACoffee(r1);
case 6:
r2 = _context.sent;
_context.next = 9;
return clearTheTable(r2);
case 9:
r3 = _context.sent;
return _context.abrupt("return", { r1: r1, r2: r2, r3: r3 });
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](0);
console.warn(_context.t0);
throw _context.t0;
case 17:
case "end":
return _context.stop();
}
}
}, _callee, this, [[0, 13]]);
}));
return function exampleF() {
return _ref.apply(this, arguments);
};
}();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment