Skip to content

Async Functions

Basics

Task 1: Create a regular function that returns Sync Hi.

function hi1(){
  return 'Sync Hi'
}

let syncHi = hi1()
console.log(syncHi)

The result is: Sync Hi

Task 2: Check the following code, and compare the result to task 1.

async function hi2(){
  return 'Async Hi'
}

let asyncHi = hi2()
console.log(asyncHi)

The result is:

Promise { <state>: "fulfilled", <value>: "Async Hi" }

Async Functions

Async functions return a promise.

Task 3: Display the value of the returned promises in task 2.

async function hi2(){
  return 'Async Hi'
}

let asyncHi = hi2()
asyncHi.then(value => console.log(value))

The result is: Async Hi

Task 4: Convert the following function to async function, and display its value in the console.

//function m10(num) {
//  return num * 10;
//}

async function m10(num) {
  return num * 10;
}
m10(10).then((value) => console.log(value));
m10(null).then((value) => console.log(value));
m10(undefined).then((value) => console.log(value));

The result is:

100
0
NaN

Task 5: Convert the following function to async function, and display its value in the console.

//const createObj = (key, val) => {
//  let obj = {};
//  obj[key] = val;
//  return obj;
//};

const createObj = async (key, val) => {
  let obj = {};
  obj[key] = val;
  return obj;
};
createObj("num", 5).then((obj) => console.log(obj));

The result is: Object {num: 5}


await

Task 6: Check the following code.

const hi = () => {
  return new Promise((resolve) => setTimeout(resolve, 2000, "hi"));
};
const getHi = async () => {
  let x = await hi();
  console.log(x);
};
getHi();

The result is: hi

await

The await operator is used to wait for a promise. It returned the fulfilled value of the promise.

Task 7: Re-write the code in task 4 in the same way the task 6 code is written.

function m10(num) {
  return new Promise((resolve) => setTimeout(resolve, 2000, num * 10));
}
async function m10Async(num) {
  let result = await m10(num);
  console.log(result)
}
m10Async(10)

The result is: 100

Task 8: Re-write the code in task 5 in the same way the task 6 code is written.

const createObj = (key, val) => {
  let obj = {};
  obj[key] = val;
  return new Promise((resolve) => setTimeout(resolve, 2000, obj));
};
const createObjAsync = async (key, val) => {
  let obj = await createObj(key, val);
  console.log(obj);
};
createObjAsync("num", 5);

The result is: Object {num: 5}


Returns a promise

Task 9: Refer to task 6; what is the value returned from the getHi function.

const hi = () => {
  return new Promise((resolve) => setTimeout(resolve, 2000, "hi"));
};
const getHi = async () => {
  let x = await hi();
  return x;

};
console.log(getHi())

The result is: Promise { <state>: "pending" }

Async Functions reutns a promise (repeat)

Task 10: Refer to task 9; get the value from the returned promise.

const hi = () => {
  return new Promise((resolve) => setTimeout(resolve, 2000, "hi"));
};
const getHi = async () => {
  let x = await hi();
  return x;
};
getHi().then(val => console.log(val))

The result is: hi


Try/catch

Task 11: Check the following code.

function checkValue(value) {
  return new Promise((resolve, reject) => {
    if (value === undefined) {
      reject("Invalid value");
    } else {
      resolve(value);
    }
  });
}
checkValue(undefined)
  .then((value) => console.log(value))
  .catch((error) => console.log(error));
checkValue(5)
  .then((value) => console.log(value))
  .catch((error) => console.log(error));

The result is:

5
Invalid value

Task 12: Check the following code.

function checkValue(value) {
  return new Promise((resolve, reject) => {
    if (value === undefined) {
      reject("Invalid value");
    } else {
      resolve(value);
    }
  });
}
async function checkValueAsync(val) {
  try {
    let x = await checkValue(val);
    console.log(x);
  } catch (error) {
    console.log(error);
  }
}
checkValueAsync(undefined);
checkValueAsync(10);

The result is:

Invalid value
10

Note

You can catch the errors in the async functions using the try/catch statement.


Some Practice

Task 13: Do the following steps:

  1. Create a regular function that returns a promise.
  2. If the given value is equal to "done", the promise is resolved. Otherwise, it is rejected.
  3. The promise is resolved after 4 seconds with the response 200.
  4. The promised is rejected after 3 seconds with the resopnse 403
  5. Call the created function in an async function
  6. Capture the error with try/catch statement.
function myfunc(val) {
  return new Promise((resolve, reject) => {
    if (val === "done") {
      setTimeout(resolve, 4000, 200);
    } else {
      setTimeout(reject, 3000, 403);
    }
  });
}
async function myfuncAsync(val) {
  try {
    let res = await myfunc(val);
    console.log(res);
  } catch (error) {
    console.log(error);
  }
}

myfuncAsync("done");
myfuncAsync(5);

The result is:

403
200

Task 14: Do the following steps:

  1. Create a regular function that returns a promise.
  2. If the given value is less than 0, the promise is resolved. Otherwise, it is rejected.
  3. The promise is resolved after 1 seconds with the response {val: val, state: "ok"}.
  4. The promised is rejected after 1 seconds with the response {val: val, state: "ko"}
  5. Call the created function in an async function
  6. Capture the error with try/catch statement.
function myfunc(val) {
  return new Promise((resolve, reject) => {
    if (val < 0) {
      setTimeout(resolve, 1000, {val: val, state: "ok"});
    } else {
      setTimeout(reject, 1000, {val: val, state: "ko"});
    }
  });
}
async function myfuncAsync(val) {
  try {
    let res = await myfunc(val);
    console.log(res);
  } catch (error) {
    console.log(error);
  }
}

myfuncAsync(-7);
myfuncAsync(1);

The result is:

Object { val: -7, state: "ok" }
Object { val: 1, state: "ko" }