Asynchronous Typescript: Callbacks, Promises, Async, Await, RxJS

Function

1
2
3
4
5
6
function printMessage(message: string) {
  console.log(message);
}

// usage
printMessage("Function");
1
2
# output
Function

Arrow Function

1
2
3
4
5
6
const printMessageArrow = (message: string) => {
  console.log(message);
};

// usage
printMessageArrow("Arrow Function");
1
2
# output
Arrow Function

Calling One Function from Another

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const printMessage = (message: string) => {
  console.log(message);
};

const getMessage = () => {
  const message = "Function Calling Another Function";
  printMessage(message);
};

// usage
getMessage();
1
2
# output
Function Calling Another Function

Async Function

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const printMessage = (message: string) => {
  console.log(message);
};

const getMessageAsync = () => {
  const message = "Async Function";
  setTimeout(() => {
    printMessage(message);
  }, 1000);
};

// usage
console.log("start");
getMessageAsync(); // prints after 1000 milliseconds
console.log("end");
1
2
3
4
# output
start
end
Async Function

Async Function With a Callback

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const printMessage = (message: string) => {
  console.log(message);
};

const getMessageWithCallback = (callback: Function) => {
  const message = "Async Function with a Callback Function";
  setTimeout(() => {
    callback(message);
  }, 1000);
};

// usage
getMessageWithCallback((message: string) => {
  printMessage(message);
});

// usage 2
getMessageWithCallback(printMessage);
1
2
# output
Async Function with a Callback Function

Async Function With a Callback and a Variable

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const printMessage = (message: string) => {
  console.log(message);
};

const getMessageWithVariables = (message: string, callback: Function) => {
  setTimeout(() => {
    callback(message);
  }, 1000);
};

// usage
getMessageWithVariables(
  "Async Function with a Callback Function and a Variable",
  (message: string) => printMessage(message)
);

// usage 2
getMessageWithVariables(
  "Async Function with a Callback Function and a Variable",
  printMessage
);
1
2
# output
Async Function with a Callback Function and a Variable

Promises

Simple Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const printMessage = (message: string) => {
  console.log(message);
};

const getMessagePromise = (message: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(message);
      reject(new Error("Promise Error"));
    }, 1000);
  });
};

// usage
getMessagePromise("Async Function Returning A Promise").then(
  (message: string) => {
    printMessage(message);
  }
);

// usage 2
getMessagePromise("Async Function Returning A Promise").then(printMessage);
1
2
# output
Async Function Returning A Promise

Complete Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const printMessage = (message: string) => {
  console.log(message);
};

const trueFalse = (): boolean => {
  return Math.random() < 0.5;
};

const getMessagePromiseFull = (message: string) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      trueFalse() ? resolve(message) : reject(new Error("Message Error"));
    }, 1000);
  });
};

// usage
getMessagePromiseFull(
  "Async Function Returning a Promise with a Message or an Error"
)
  .then((message) => printMessage(<string>message))
  .catch((err) => console.log(err.message))
  .finally(() => console.log(`Promise resolved`));
1
2
3
# output
Async Function Returning a Promise with a Message or an Error
Promise Resolved

Division Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const printResult = (result: number) => {
  console.log(result);
};

const divide = (a: number, b: number): Promise<number> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (b === 0) reject(new Error("Division Error!"));
      resolve(a / b);
    }, 1000);
  });
};

// usage - success
divide(4, 2)
  .then(printResult)
  .catch((err) => console.log(err.message))
  .finally(() => console.log("Operation Complete")); // optional

// usage - error
divide(1, 0)
  .then(printResult)
  .catch((err) => console.log(err.message))
  .finally(() => console.log("Operation Complete")); // optional
1
2
3
4
5
6
7
# output for (4, 2)
2
Operation Complete

# output for (1, 0)
Division Error
Operation Complete

Async / Await

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const printMessage = (message: string) => {
  console.log(message);
};

const trueFalse = (): boolean => {
  return Math.random() < 0.5;
};

const getMessagePromiseFull = (message: string) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      trueFalse() ? resolve(message) : reject(new Error("Message Error"));
    }, 1000);
  });
};

const getMessages = async () => {
  try {
    const message1 = await getMessagePromiseFull("Promise Example Message 1");
    console.log(message1);
    const message2 = await getMessagePromiseFull("Promise Example Message 2");
    console.log(message2);
  } catch (err: any) {
    console.log("Error:", err.message);
  }
};

// usage
getMessages();
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# output
Error: Message Error

# output
Promise Example Message 1
Error: Message Error

# output
Promise Example Message 1
Promise Example Message 2

Division Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const printResult = (result: number) => {
  console.log(result);
};

const printOddEven = (value: number) => {
  value % 2 === 0
    ? console.log("Result is even")
    : console.log("Result is odd");
};

const divide = (a: number, b: number): Promise<number> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (b === 0) reject(new Error("Division Error!"));
      resolve(a / b);
    }, 1000);
  });
};

const addOne = (a: number): Promise<number> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(a + 1);
    }, 1000);
  });
};

const calculate = async (a: number, b: number) => {
  try {
    const division = await divide(a, b);
    const result = await addOne(division);
    printResult(result);
    printOddEven(result);
  } catch (err) {
    console.log(err.message);
  }
};

// usage
calculate(4, 2);
1
2
3
# output
3
Result is odd

Division Example with Return

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const printResult = (result: number) => {
  console.log(result);
};

const printOddEven = (value: number) => {
  value % 2 === 0
    ? console.log("Result is even")
    : console.log("Result is odd");
};

const divide = (a: number, b: number): Promise<number> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (b === 0) reject(new Error("Division Error!"));
      resolve(a / b);
    }, 1000);
  });
};

const addOne = (a: number): Promise<number> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(a + 1);
    }, 1000);
  });
};

const calculate = async (a: number, b: number): Promise<number> => {
  const division = await divide(a, b);
  const result = await addOne(division);
  return result;
};

// usage
calculate(4, 2)
  .then((result) => {
    printResult(result);
    printOddEven(result);
  })
  .catch((err) => console.log(err.message))
  .finally(() => console.log("Operation Complete."));
1
2
3
4
# output
3
Result is odd
Operation Complete.

RxJS

TODO

comments powered by Disqus