Created
May 6, 2016 03:19
-
-
Save d4dilip/86854341aacaa2329f99f4edbe247921 to your computer and use it in GitHub Desktop.
Javascript Promise Example
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
// simulation library | |
function asyncLib() { | |
return { | |
CallfnSyncLib: CallfnSyncLib | |
} | |
function CallfnSyncLib(params) { | |
return new Promise(function(resolve, reject) { | |
fnSyncLib(params, resolve, reject); | |
}); | |
} | |
} |
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
<!DOCTYPE html> | |
<html> | |
<!-- fallback for browsers which do not support promise --> | |
<script src="es6-promise.min.js"></script> | |
<script src="syncLib.js"></script> | |
<script src="asyncLib.js"></script> | |
<script> | |
function onSuccess(response) | |
{ | |
document.getElementById("divresponse").innerHTML = response; | |
} | |
function onError(error) | |
{ | |
document.getElementById("divresponse").innerHTML = error.message; | |
} | |
function demoCallPromiseFn(params){ | |
document.getElementById("divresponse").innerHTML = "computing...."; | |
var objsyncLib=asyncLib(); | |
objsyncLib.CallfnSyncLib(params).then(onSuccess, onError); | |
} | |
</script> | |
<body onload="javascript:demoCallPromiseFn(null);"> | |
<div id="divresponse"> | |
</div> | |
</body> | |
</html> |
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
// simulation library | |
function fnSyncLib(params, onSuccess, onError) { | |
function fnTry(fn) { | |
try { | |
return fn(); | |
} catch (ex) { | |
console.log(ex.message + "\r\n\r\n" + ex.stack); | |
fnOnError(ex); | |
} | |
} | |
function fnOnError(error) { | |
console.log("fnSyncLib error: " + error.message); | |
onError(error); | |
} | |
function fnSimulateRemoteCall() { | |
var startdate = new Date().getTime(); | |
//hang on for a while | |
sleepFor(5000); | |
var endDate = new Date().getTime(); | |
console.log(startdate); | |
console.log(endDate); | |
var response = "It took me 5 seconds"; | |
onSuccess(response); | |
} | |
function sleepFor(sleepDuration) { | |
var now = new Date().getTime(); | |
while (new Date().getTime() < now + sleepDuration) { /* do nothing */ } | |
} | |
// initialize function here | |
fnTry(fnSimulateRemoteCall); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment