19
loading...
This website collects cookies to deliver better user experience
async
is a keyword that you put in front of a function to make it an async function. So all of these are examples of async function declaration.async function doSomething(){ ... }
var doSomethingElse = async function(){ ... }
var doSomethingMore = async () => { ... }
async function returnValue() {
return 1;
}
returnValue()
.then( console.log );
// 1
async function throwError() {
throw "oh no!";
}
throwError()
.catch( console.log );
// "oh no!"
async function returnPromise() {
return Promise.resolve(2);
}
returnPromise()
.then( console.log );
// 2
await
keyword is placed in front of a promise object and signals JS to suspend execution of any consecutive statement until the promise is settled. It can only be used inside an async function.async function doSomething() {
var promise = new Promise( resolve => {
setTimeout( () => resolve( 1 ), 1000 );
});
var fulfilledValue = await promise;
console.log( fulfilledValue );
};
doSomething();
// 1
doSomething()
is invoked, JS starts executing the statements inside it synchronously. The first statement executes synchronously meaning a new Promise is created and assigned to the variable promise
. The next statement has an await
keyword and when JS encouters this keyword, it pauses the execution of doSomething()
. While the execution of doSomething()
is paused, JS works on executing other stuff like updating the DOM or responding to user interactions. After 1 second, when promise
is fulfilled with the value 1, JS again resumes execution of the doSomething()
and assigns the fulfilled value 1 to fulfilledValue
. It then executes the console.log()
and logs this fulfilled value onto the console.await
keyword in top-level code or inside a function which is not async. It will lead to an error. It only works inside an async function. For example, if we remove the async
keyword from the above function, it will lead to an error.function doSomething() {
var promise = new Promise( resolve => {
setTimeout( () => resolve( 1 ), 1000 );
});
var fulfilledValue = await promise;
console.log( fulfilledValue );
};
doSomething();
// Uncaught SyntaxError: await is only valid in async functions and async generators
await
keyword will forward the error.async function doSomething() {
var promise = new Promise((resolve, reject) => {
setTimeout(() => reject("oh no!"), 1000);
});
await promise;
};
doSomething();
// Uncaught (in promise) oh no!
try
-catch
block.async function doSomething() {
try {
var promise = new Promise( (resolve, reject) => {
setTimeout(() => reject("oh no!"), 1000);
});
await promise;
} catch (err) {
console.log(err);
}
};
doSomething();
// "oh no!"
catch()
on the returned promise.async function doSomething() {
var promise = new Promise((resolve, reject) => {
setTimeout(() => reject("oh no!"), 1000);
});
await promise;
};
doSomething().catch(console.log);
// "oh no!"
// fetch all repos
fetch("https://api.github.com/users/saurabh-misra/repos")
.then( response => response.json() )
// return the github URL of the 3rd repo in the list
.then( repos => repos[2].url )
// fetch details for this repo
.then( repoUrl => fetch(repoUrl) )
.then( response => response.json() )
.then( repoInfo => {
console.log("Name: ", repoInfo.name);
console.log("Description: ", repoInfo.description);
})
.catch( error => console.log("Error: ", error) );
/*
Name: pomodoro-timer
Description: A simple pomodoro timer web app
that helps you focus on your work.
*/
async function getRepoInfo() {
// fetch repos and parse JSON
var repoUrl = "https://api.github.com/users/saurabh-misra/repos";
var reposResponse = await fetch(repoUrl);
var repos = await reposResponse.json();
// fetch info on one of the repos
var repoInfoResponse = await fetch(repos[2].url)
var repoInfo = await repoInfoResponse.json();
return repoInfo;
}
getRepoInfo()
.then(repoInfo => {
console.log("Name: ", repoInfo.name);
console.log("Description: ", repoInfo.description);
})
.catch(console.log);
/*
Name: pomodoro-timer
Description: A simple pomodoro timer web app
that helps you focus on your work.
*/
// pseudo code
fetch( /*store cc details*/ )
.then( () => fetch( /*verify response*/ ))
.then( () => fetch( /*make first payment*/ ))
.then( () => fetch( /*verify response*/ ))
.then( () => fetch( /*make second payment*/ ))
.then( () => fetch( /*verify response*/ ))
.then( () => fetch( /*mark order as complete*/ ))
.catch( () => {
// handle errors
})
.finally( () => {
// perform clean up
});
// pseudo code
async function doPayment() {
var storeCCDetailsresponse = await fetch("store cc details");
await fetch("verify response");
var firstPaymentResponse = await fetch("make first payment");
await fetch("verify response");
var secondPaymentResponse = await fetch("make second payment");
await fetch("verify response");
await fetch("mark order as complete");
};
doPayment()
.catch(console.log);
.finally(() => {
// perform clean-up code.
});
promisifyTimeout()
to basically make setTimeout()
return a promise and fulfill it when the timeout occurs.function promisifyTimeout(interval) {
return new Promise(resolve => {
setTimeout(resolve, interval);
});
}
async function startParallelTimers() {
await promisifyTimeout(1000);
console.log("1st timer done."); // executes after 1 second
await promisifyTimeout(1000);
console.log("2nd timer done."); // executes after 2 seconds
await promisifyTimeout(1000);
console.log("3rd timer done."); // executes after 3 seconds
}
startParallelTimers();
/*
1st timer done.
2nd timer done.
3rd timer done.
*/
await
keywords makes them run sequentially instead i.e the second timer cannot start until the first is done.await
keywords.function promisifyTimeout( interval ) {
return new Promise( resolve => {
setTimeout(resolve, interval);
});
}
async function startParallelTimers() {
var firstTimeoutPromise = promisifyTimeout(1000);
var secondTimeoutPromise = promisifyTimeout(1000);
var thirdTimeoutPromise = promisifyTimeout(1000);
await firstTimeoutPromise;
console.log("1st timer done.");
await secondTimeoutPromise;
console.log("2nd timer done.");
await thirdTimeoutPromise;
console.log("3rd timer done.");
}
startParallelTimers();
/*
1st timer done.
2nd timer done.
3rd timer done.
*/
await
which is to initiate them without using await
and get the promise objects for each of them and then await the promise objects later.await
works with any function that returns a promise, it plays well with any of the Promise API methods. Here is an example of how it can work with Promise.all()
function promisifyTimeout( fulfilledValue, interval ) {
return new Promise( resolve => {
setTimeout(() => resolve(fulfilledValue), interval);
});
}
async function startParallelTimers() {
var firstTimeoutPromise = promisifyTimeout(1, 1000);
var secondTimeoutPromise = promisifyTimeout(2, 1000);
var thirdTimeoutPromise = promisifyTimeout(3, 1000);
var values = await Promise.all([
firstTimeoutPromise,
secondTimeoutPromise,
thirdTimeoutPromise
]);
return values;
}
startParallelTimers().then(console.log);
/*
Array(3) [ 1, 2, 3 ]
*/
await
plays well with thenables also.var thenable = {
then: function(onFulfilled, onRejected) {
setTimeout(() => onFulfilled(1), 1000);
}
};
async function testAwaitWithThenable() {
return await thenable;
}
testAwaitWithThenable().then(console.log);
// 1
await
inside them.function promisifyTimeout(fulfilledValue, interval) {
return new Promise(resolve => {
setTimeout(() => resolve(fulfilledValue), interval);
});
}
class Person {
async displayGreetingAfterTimeout() {
return await promisifyTimeout("Hello👋", 1000);
}
}
new Person()
.displayGreetingAfterTimeout()
.then(console.log);
// Hello👋
async
keyword always return a Promise.await
keyword is placed in front of a promise object and can be used to pause the execution of an async function until the promise settles.async
/await
make async code look synchronous.