Skip to content

Instantly share code, notes, and snippets.

@gparvind
Last active March 2, 2022 09:15
Show Gist options
  • Save gparvind/55842e1b5e8ddb5b816c3c4040b4a8c7 to your computer and use it in GitHub Desktop.
Save gparvind/55842e1b5e8ddb5b816c3c4040b4a8c7 to your computer and use it in GitHub Desktop.
async await examples
async function callerFunction123(){
var result = await fnName123();
console.log( result );//will print "value_123"
}
async function fnName123(){/*code here*/}
async function fnName123() {
return new Promise((resolve, reject) => {
//either call resolve for success response with the result ->
resolve("value_123");
//or call reject for error response with the error info ->
reject(new Error("error reason");
});
}
//setTimeout wrapper as async function.
async function setTimeoutAsync(fn, ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
var result = fn();
resolve(result);
} catch (err) {
reject(err);
}
}, ms);
});
}
//user code that uses sleep function
async function userCode() {
//do something
console.log("1");
//invoke a function after every 1s 3 times.
for (var i = 0; i < 3; i++) {
var result = await setTimeoutAsync(() => { return "value123=" + i; }, 1000);
console.log(i + "->" + result);
}
//do something more
console.log("2");
}
userCode();//run it for testing.
//sleep function as async function using setTimeout internally.
async function sleep(ms){
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);//resolve is called after ms milliseconds.
});
}
//user code that uses sleep function
async function userCode(){
//do something
//sleep for 100ms
await sleep(100);
//do something more
}
userCode();//run it for testing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment