1async function f() {
2
3 try {
4 let response = await fetch('/no-user-here');
5 let user = await response.json();
6 } catch(err) {
7 // catches errors both in fetch and response.json
8 alert(err);
9 }
10}
1// Old School Javascript Invoke
2(async function() {
3 await someAsyncFunction();
4})();
5
6//New ES6 Javascript Invoke
7(async () => {
8 await someAsyncFunction();
9})();
1const data = async () => {
2 const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
3
4 console.log(await got.json())
5}
6
7data();
1async function showAvatar() {
2
3 // read our JSON
4 let response = await fetch('/article/promise-chaining/user.json');
5 let user = await response.json();
6
7 // read github user
8 let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
9 let githubUser = await githubResponse.json();
10
11 // show the avatar
12 let img = document.createElement('img');
13 img.src = githubUser.avatar_url;
14 img.className = "promise-avatar-example";
15 document.body.append(img);
16
17 // wait 3 seconds
18 await new Promise((resolve, reject) => setTimeout(resolve, 3000));
19
20 img.remove();
21
22 return githubUser;
23}
24
25showAvatar();
1function resolveAfter2Seconds() {
2 return new Promise(resolve => {
3 setTimeout(() => {
4 resolve('resolved');
5 }, 2000);
6 });
7}
8
9//async function:
10async function asyncCall() {
11 console.log('calling');
12 const result = await resolveAfter2Seconds();
13 console.log(result);
14 // expected output: 'resolved'
15}
16
17asyncCall();
1// The await operator in JavaScript can only be used from inside an async function.
2// If the parameter is a promise, execution of the async function will resume when the promise is resolved
3// (unless the promise is rejected, in which case an error will be thrown that can be handled with normal JavaScript exception handling).
4// If the parameter is not a promise, the parameter itself will be returned immediately.[13]
5
6// Many libraries provide promise objects that can also be used with await,
7// as long as they match the specification for native JavaScript promises.
8// However, promises from the jQuery library were not Promises/A+ compatible until jQuery 3.0.[14]
9
10async function createNewDoc() {
11 let response = await db.post({}); // post a new doc
12 return await db.get(response.id); // find by id
13}
14
15async function main() {
16 try {
17 let doc = await createNewDoc();
18 console.log(doc);
19 } catch (err) {
20 console.log(err);
21 }
22}
23main();
24