A lightweight deferred implementation with Typescript support, inspired by jQuery and based on Javascript's Promise.
npm i @h-reser/deferred
import Deferred from "@h-reser/deferred";
// Create deferred object
const d = new Deferred();
// Implement logic
function playLottery() {
setTimeout(() => {
const random = Math.floor(Math.random() * Math.floor(2));
if (random === 1)
d.resolve("You have won!");
else d.reject("You have lost...");
}, 500);
};
// Handle Defered fulfillments and rejections
d
.then((res) => {
console.log(res + " :)");
})
.catch((e) => {
console.error(e + " :(");
})
.finally(() => {
console.log("Thanks for playing!");
});
// Execute logic
playLottery();
Can be used in any environment which supports ES6's promises