From 78464b9525185caab8ca1f93a78433442c4b9299 Mon Sep 17 00:00:00 2001 From: xfarrow Date: Mon, 9 Oct 2023 17:56:10 +0200 Subject: [PATCH] Create async-await.js --- backend/tutorials/async-await.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 backend/tutorials/async-await.js diff --git a/backend/tutorials/async-await.js b/backend/tutorials/async-await.js new file mode 100644 index 0000000..3b35745 --- /dev/null +++ b/backend/tutorials/async-await.js @@ -0,0 +1,26 @@ +// https://javascript.info/async-await + +// A async function always returns a promise. Other values are wrapped in a resolved promise automatically. + +async function f1() { + return 1; + } + + f1().then(console.log); // 1 + +// The keyword await makes JavaScript wait until that promise settles and returns its result. +// It can be used in async functions only +// Let’s emphasize: await literally suspends the function execution until the promise settles, +// and then resumes it with the promise result. +async function f2() { + + let promise = new Promise((resolve, reject) => { + setTimeout(() => resolve("done!"), 1000) + }); + + let result = await promise; // wait until the promise resolves (*) + + console.log(result); // "done!" + } + + f2(); \ No newline at end of file