diff --git a/async-await/0_callbacks.js b/async-await/0_callbacks.js index 77c2b57..57a7fcb 100644 --- a/async-await/0_callbacks.js +++ b/async-await/0_callbacks.js @@ -1,31 +1,30 @@ // https://javascript.info/callbacks -entryPoint(); +entryPoint() function entryPoint () { - - execute_action('something', function (error, time_of_completion) { - if (error) { - console.log('Something happened'); - } else { - console.log('Time of completion: ' + new Date(time_of_completion).toDateString()); - } - }); - console.log("I don't need execute_action's value"); - } - - function execute_action (param, callback) { - if (param == 'something') { - console.log('Executing action: ' + param); - callback(null, Date.now()); + execute_action('something', function (error, time_of_completion) { + if (error) { + console.log('Something happened') } else { - // We can call callback with one argument even if - // the signature states two parameters. - callback(new Error('Invalid parameter')); + console.log('Time of completion: ' + new Date(time_of_completion).toDateString()) } - } + }) + console.log("I don't need execute_action's value") +} - /* +function execute_action (param, callback) { + if (param == 'something') { + console.log('Executing action: ' + param) + callback(null, Date.now()) + } else { + // We can call callback with one argument even if + // the signature states two parameters. + callback(new Error('Invalid parameter')) + } +} + +/* This is useful when, for example, execute_action performs slow operations (such as I/O, HTTP requests etc) and we need its result to continue a specific operation (in this case the date of completion), without blocking @@ -46,12 +45,11 @@ function entryPoint () { asynchronous function, such as setTimeout(callback, delay). - Callbacks are not asynchronous by nature, but can be used + Callbacks are not asynchronous by nature, but can be used for asynchronous purposes. The problem is that this makes the code harder to read so modern JS is written using Promises and async/await constructs. - + */ - \ No newline at end of file diff --git a/async-await/1_promises.js b/async-await/1_promises.js index 034267b..264b669 100644 --- a/async-await/1_promises.js +++ b/async-await/1_promises.js @@ -3,7 +3,7 @@ /* The function passed to Promise is called "executor" and gets executed synchronously and immediately after the Promise is created. - When the Promise ends, the callback function should + When the Promise ends, the callback function should either call the "resolve" or "reject" callbacks: resolve(value) — if the job is finished successfully, with result value. reject(error) — if an error has occurred, error is the error object. @@ -13,14 +13,14 @@ - Fullfilled (the operation has completed successfully, resolve has been called) - Rejected (the operation has not completed successfully, reject has been called) - A promise represents the completion of a (likely) asynchronous function. It is an object + A promise represents the completion of a (likely) asynchronous function. It is an object that might return a value in the future. It accomplishes the same basic goal as a callback function, but with many additional features and a more readable syntax. */ const promise = new Promise(function (resolve, reject) { - setTimeout(() => resolve('done'), 5000); -}); - + setTimeout(() => resolve('done'), 5000) +}) + /* The first argument of .then is a function that runs when the promise is resolved and receives the result. The second argument of .then is a function that runs when the promise is rejected and receives the error. @@ -29,34 +29,34 @@ const promise = new Promise(function (resolve, reject) { promise.then( result => console.log('The operation was successful. It returned ' + result), error => console.log('The operation was not successful: ' + error) -); - +) + /* Or we can pass only one argument if we're interested only in a positive result */ promise.then( result => console.log('The operation was successful. It returned ' + result) -); - +) + /* Or we can pass only one argument to the method "catch" if we're interested in negative results only. - + promise.catch internally just calls promise.then(null, f) */ promise.catch( error => console.log(error) -); - +) + /* finally gets always called */ promise.finally( () => console.log('The execution has terminated. Bye') -); +) /* This line is used to demonstrate that the code within "then, catch, etc." is in the event loop, as this is the first line getting executed. */ -console.log("Last line"); \ No newline at end of file +console.log('Last line') diff --git a/async-await/2_promise-chaining.js b/async-await/2_promise-chaining.js index df42581..cb01da3 100644 --- a/async-await/2_promise-chaining.js +++ b/async-await/2_promise-chaining.js @@ -4,45 +4,45 @@ // internally calling resolve(). new Promise(function (resolve, reject) { - setTimeout(() => resolve(1), 1); - }).then(function (result) { - console.log(result); - return result * 2; - }).then(function (result) { - console.log(result); - return result * 2; - }).then(function (result) { - console.log(result); - return result * 2; - }); - - /* + setTimeout(() => resolve(1), 1) +}).then(function (result) { + console.log(result) + return result * 2 +}).then(function (result) { + console.log(result) + return result * 2 +}).then(function (result) { + console.log(result) + return result * 2 +}) + +/* It will print 1 2 4 */ - - /* + +/* It means that "then" is internally implemented roughly as follows: - + function then(f){ return new Promise(function(resolve, reject) { resolve(f()); }) } */ - - // Another example: - - fetch('http://www.fsf.org') - // .then below runs when the remote server responds - .then(function (response) { - // response.text() returns a new promise that resolves with the full response text - // when it loads - return response.text(); - }) - .then(function (text) { - // ...and here's the content of the remote file - console.log(text); - }); \ No newline at end of file + +// Another example: + +fetch('http://www.fsf.org') +// .then below runs when the remote server responds + .then(function (response) { + // response.text() returns a new promise that resolves with the full response text + // when it loads + return response.text() + }) + .then(function (text) { + // ...and here's the content of the remote file + console.log(text) + }) diff --git a/async-await/3_async-await.js b/async-await/3_async-await.js index 26b783a..8e88ff8 100644 --- a/async-await/3_async-await.js +++ b/async-await/3_async-await.js @@ -4,23 +4,23 @@ // Async and await are merely syntactic sugar in order to make Promise usage easier async function f1 () { - return 1; + return 1 } - -f1().then(console.log); // 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 () { const promise = new Promise((resolve, reject) => { - setTimeout(() => resolve('done!'), 1000); - }); - const result = await promise; // wait until the promise resolves (*) - console.log(result); // "done!" + setTimeout(() => resolve('done!'), 1000) + }) + const result = await promise // wait until the promise resolves (*) + console.log(result) // "done!" } -f2(); +f2() // The code in the same function after "await" // is to be intended in the "then()" of the primise. This means @@ -28,15 +28,15 @@ f2(); // the flow of execution goes out that code block. For example // consider the following example: async function exampleAsyncFunction () { - console.log('Before await'); + console.log('Before await') await new Promise(function (resolve, reject) { - setTimeout(() => resolve('done'), 500); - }); // Pauses execution here until the promise resolves. - console.log('After await'); + setTimeout(() => resolve('done'), 500) + }) // Pauses execution here until the promise resolves. + console.log('After await') } -console.log('Start'); -exampleAsyncFunction(); -console.log('End'); +console.log('Start') +exampleAsyncFunction() +console.log('End') // The result will be: // Start, Before Await, End, After await