Last active
December 27, 2019 09:22
-
-
Save selcukcihan/34f2050d956943e4dd85ab53b2b25af4 to your computer and use it in GitHub Desktop.
Javascript promise chain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function callService(param, shouldThrow) { | |
return new Promise(function(resolve, reject) { | |
setTimeout(function() { | |
if (shouldThrow) { | |
reject("Hatalı: " + param); | |
} else { | |
resolve("Başarılı: " + param); | |
} | |
}, 300); | |
}); | |
} | |
function callServiceA(param) { | |
return callService(param, false); | |
} | |
function callServiceB(param) { | |
return callService(param, false); | |
} | |
function callServiceC(param) { | |
return callService(param, true); | |
} | |
function callServiceD(param) { | |
return callService(param, false); | |
} | |
function log(label, promise) { | |
let begin; | |
return (response) => { | |
return new Promise(function(resolve) { | |
begin = performance.now(); | |
console.log(`${label} başladı.`); | |
resolve(response); | |
}) | |
.then(promise) | |
.then(res => { | |
console.log(`${label} bitti. Cevap: "${res}". Geçen süre: ${(performance.now() - begin)}.`); | |
return res; | |
}); | |
}; | |
} | |
let promise = log("A servisi", callServiceA)("test") | |
.then(log("B servisi", callServiceB)) | |
.then(log("C servisi", callServiceC)) | |
.then(log("D servisi", callServiceD)) | |
.catch(console.log); | |
let result = await promise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment