The document discusses asynchronous programming concepts like callbacks, promises, and async/await in JavaScript. It provides examples of using callbacks that can result in "callback hell", and how promises and async/await can help solve this issue by making asynchronous code more readable and maintainable through chaining and avoiding nested callbacks. Key aspects covered include the event loop model, promise chaining, Promise.all/race, and using async/await with functions.
1. Модель совпадения и цикл
событий.
Асинхронное выполнение, функции
как колбэки, Promise
Masters Academy, 2018
2.
3.
4.
5. 1. Стэк (stack) контекстов
выполнения функций
программы
2. Куча (heap) -
неструктурированная
область памяти, для
хранения объектов
3. Очередь событий (queue) -
список событий, подлежащих
обработке вследствие
выполнения асинхронных
операций
35. Promise features
1. No inversion of control, you get the future value
2. Immutable after resolve/reject
3. Completes only once (resolve/reject)
4. Chainable, always returns a Promise instance
5. Lighter syntax
6. Utilizes ES6 Jobs (acts like async microtask, not task)
7. Promise.all, Promise.race and more
8. Cannot be cancelled
36. Promise Chaining
function createRequest(url) {
return new Promise((resolve, reject) => {
ajax(url, resolve, reject); // assume ajax is some http library
})
}
const promise = createRequest(‘http://auth.com’);
promise.then(createRequest).then(createRequest).catch(console.log)
37. Handy to use
Promise.all // resolves when all promises are resolved
Promise.race // resolves when one of promises is resolved
fetch // A modern replacement for XMLHttpRequest
39. Good resources
1. https://www.youtube.com/watch?v=8aGhZQkoFbQ nice video about call stack
and event loop
1. https://medium.com/front-end-hacking/callbacks-promises-and-async-await-
ad4756e01d90 callback, Promise, async/await concepts
1. https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
tasks vs microtasks in event loop
40. Homework
Create a function logNumbers() which accepts one argument of type ‘number’.
After one second log into console this number + 10.
After two seconds log into console previous step result * 3.
After three seconds log into console previous step result - 20.
Provide callback, Promise and async/await based solution.
41. Homework ** (only if you get bored with first one)
fetch() is cool for HTTP requests. It’s Promise-based and has lots of options. But
as Promise resolves/rejects only once and stays immutable, we cannot use it for
reporting file upload progress purposes (PUT). Create a function which would
provide a possible solution for this.
Hint: this function will not use fetch()