top of page
ashutoshsharma52

What is Async Wait???

Where to Find ASYNC Request

Promises are a typical construct that help you deal with asynchronous code because promises work like that. Post find gets executed and count documents also gets executed immediately but then this actually, count documents returns a promise or a promise-like object and you then use then to define a function that should be executed once this operation here is done and since we access the database here, this typically takes a bit longer. We're talking about milliseconds here but still it doesn't happen instantly. On the opposite, this line and this line get executed after each other instantly, this operation does essentially not take any time at all, it's so fast javascript can wait for it to complete and move onto the next step right away. Here it will not wait for that to complete and that is why after this statement, JavaScript would actually move on with the next statement inline, so if we had another statement on the same level as post find, we would continue with that. Now in this case we got none but if we would have some code there, like a console log or anything, this would execute right away, probably or very likely before this or this code or this code was executed and the reason for that is that with then, we define code snippets or we define functions that should run in the future once this longer taking asynchronous operation is done and it's called asynchronous because it doesn't happen instantly but it takes a little while. Callbacks which we used earlier in the course are another way of working with asynchronous code, so here too for count documents, you could actually and you see that here in the documentation that pops up, you could define a callback function. So here you could define a function that gets executed once it's done instead of then and we don't use callbacks because in there, we would use that code and then we would need a callback here in the find function and we would nest all these callbacks leading to very unreadable code.

That is why you often prefer promises even though you could do it with callbacks because there, you have one then block after each other and it's very readable. Still it can get more readable with async and await


let me introduce you to async await. To use that, you first of all have to prepend the async keyword in front of a function, like this arrow function here, so this function where you plan to use the await keyword, so where you want to use these two keywords, they always are used together, async in front of the function

2 views0 comments

Recent Posts

See All

SQL UNION GROUP BY

SQL UNION Operator UNION operator is used to combine the results of two or more SELECT statements Every SELECT statement within UNION...

SQL JOIN

JOIN clause is used to combine rows from two or more tables. INNER JOIN === selects records that have matching values in both tables...

Comments


bottom of page