3.52M
Категория: ПрограммированиеПрограммирование

Asynchronou s JavaScript

1.

Asynchronou
s JavaScript

2.

Contents
• How it was before
• Introducing promises and how actually asynchronous JS works
• Promise hell
• Async/await and why it is good

3.

How it was before
$.ajax({
type: "GET",
url: settings.ajaxUrl,
data: dataParams,
success: function (data) {
controls.contentContainer.html(data);
adjustWindowSize();
if (self && self.getIsOpened()) {
var tracker = self.getFocusTracker();
if (tracker) {
tracker.startTrackFocus();
}
}
CommonFunctions.safeExecuteFunction(customScripts.afterOpenDialogAjaxDynamicallySuccess);
},
error: function (xhr, status, error) {
CommonFunctions.alertAjaxError(xhr, status, error);
}
});

4.

Please
Don’t

5.

Introducing promises
The Promise object represents the eventual completion (or
failure) of an asynchronous operation and its resulting value.
new Promise((resolve, reject) => {
try {
resolve(777);
} catch (error) {
reject(error);
}
})
.then(value => console.log('asynchronous logging has value:', value))
.catch(error => console.log(error));

6.

const promiseA = new Promise((resolve, reject) => {
resolve(777);
});
// At this point, "promiseA" is already settled.
promiseA.then(value => console.log("asynchronous logging has value:", value));
console.log("immediate logging");
// produces output in this order:
// immediate logging
// asynchronous logging has val: 777

7.

Event loop
The event loop is the secret behind JavaScript’s asynchronous
programming. JS executes all operations on a single thread, but
using a few smart data structures, it gives us the illusion of multithreading. Let’s take a look at what happens on the back-end.
Within the Event Loop, there are actually 2 type of queues: the
(macro)task queue (or just called the task queue), and the
microtask queue. The (macro)task queue is for (macro)tasks and
the microtask queue is for microtasks.

8.

Microtask
A microtask is a short function which is executed after the
function or program which created it exits and only if
the JavaScript execution stack is empty.
• Promise callback
• queueMicrotask
Macrotask
A macrotask is short function which is executed after JavaScript
execution stack and microtask are empty.
• setTimeout
• setInterval
• setImmediate

9.

All functions in that are currently in the call stack get executed.
When they returned a value, they get popped off the stack.
When the call stack is empty, all queued up microtasks are
popped onto the callstack one by one, and get executed!
(Microtasks themselves can also return new microtasks,
effectively creating an infinite microtask loop)
If both the call stack and microtask queue are empty, the
event loop checks if there are tasks left on the (macro)task
queue. The tasks get popped onto the callstack, executed, and
popped off!

10.

How it works

11.

Promise hell
connectDatabase()
.then((database) => {
return findAllBooks(database)
.then((books) => {
return getCurrentUser(database)
.then((user) => {
return pickTopRecommendation(books, user);
});
});
});

12.

return getCurrentUser()
.then((user) => attachFavouriteFood
? getFood(user.favouriteFoodId)
.then((food) => {
user.food = food;
return user;
})
: user
)
.then((user) => attachSchool
? getSchool(user.schoolId)
.then((school) => {
user.school = school;
return attachFaculty
? getUsers(school.facultyIds)
.then((faculty) => {
user.school.faculty = faculty;
return user;
})
: user;
})
: user);

13.

14.

Async/await and why it is good
There’s a special syntax to work with promises in a more
comfortable fashion, called “async/await”. It’s surprisingly easy to
understand and use.
• async ensures that the function returns a promise, and wraps nonpromises in it.
• The keyword await makes JavaScript wait until that promise settles
and returns its result.

15.

async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait until the promise resolves (*)
alert(result); // "done!"
}

16.

Comparison to C#
C#
JS
Traditional Method
Callbacks
Callbacks
Underlying
Task
Promise
Invoke
Immediately
Immediately
The operation is executed
immediately after calling
the async method
The operation is executed
immediately after calling
the async method
Postpone Execution
Wrap in a Lambda expression
Wrap in a function
Use Cases
I/O & CPU-bound tasks
I/O
Multithread
Use Task.run
NO
JS is singlethreaded, Promise doesn’t help
with CPU-bound tasks

17.

Thank you!
English     Русский Правила