Skip to content

Instantly share code, notes, and snippets.

@AhmedHelalAhmed
Last active January 2, 2021 19:09
Show Gist options
  • Save AhmedHelalAhmed/65d222b4f8bbd15f439c77e89340c4ed to your computer and use it in GitHub Desktop.
Save AhmedHelalAhmed/65d222b4f8bbd15f439c77e89340c4ed to your computer and use it in GitHub Desktop.
JS chain promises
//======> output: 1 2 3 4
// synchronous - ملتزم بالترتيب
// JavaScript is always synchronous
function step1() {
return new Promise((resolve, reject) => {
console.log("1");
resolve(1);
});
}
function step2() {
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log("2");
resolve(1);
}, 3000);
});
}
function step3() {
return new Promise((resolve, reject) => {
console.log("3");
resolve(1);
});
}
function step4() {
return new Promise((resolve, reject) => {
setTimeout(function () {
console.log("4");
resolve(1);
}, 1000);
});
}
step1().then(step2).then(step3).then(step4);
//======> output: 1 3 4 2
// asynchronous - مش ملتزم بالترتيب
console.log("1");
setTimeout(function () {
console.log("2");
}, 3000);
console.log("3");
setTimeout(function () {
console.log("4");
}, 1000);
//======> we need it to be 1 2 3 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment