admin管理员组文章数量:1135071
I have been using ECMAScript 6 and ECMAScript 7 features already (thanks to Babel) in my applications - both mobile and web.
The first step obviously was to ECMAScript 6 levels. I learnt many async patterns, the promises (which are really promising), generators (not sure why the * symbol), etc. Out of these, promises suited my purpose pretty well. And I have been using them in my applications quite a lot.
Here is an example/pseudocode of how I have implemented a basic promise-
var myPromise = new Promise(
function (resolve,reject) {
var x = MyDataStore(myObj);
resolve(x);
});
myPromise.then(
function (x) {
init(x);
});
As time passed, I came across ECMAScript 7 features, and one of them being ASYNC
and AWAIT
keywords/functions. These in conjunction do great wonders. I have started to replace some of my promises with async & await
. They seem to add great value to programming style.
Again, here is a pseudocode of how my async, await function looks like-
async function myAsyncFunction (myObj) {
var x = new MyDataStore(myObj);
return await x.init();
}
var returnVal = await myAsyncFunction(obj);
Keeping the syntax errors (if any) aside, both of them do the exact same thing is what I feel. I have almost been able to replace most of my promises with async,awaits.
Why is async,await needed when promises do a similar job?
Does async,await solve a bigger problem? Or was it just a different solution to callback hell?
As I said earlier, I am able to use promises and async,await to solve the same problem. Is there anything specific that async await solved?
Additional notes:
I have been using async,awaits and promises in my React projects and Node.js modules extensively. React especially have been an early bird and adopted a lot of ECMAScript 6 and ECMAScript 7 features.
I have been using ECMAScript 6 and ECMAScript 7 features already (thanks to Babel) in my applications - both mobile and web.
The first step obviously was to ECMAScript 6 levels. I learnt many async patterns, the promises (which are really promising), generators (not sure why the * symbol), etc. Out of these, promises suited my purpose pretty well. And I have been using them in my applications quite a lot.
Here is an example/pseudocode of how I have implemented a basic promise-
var myPromise = new Promise(
function (resolve,reject) {
var x = MyDataStore(myObj);
resolve(x);
});
myPromise.then(
function (x) {
init(x);
});
As time passed, I came across ECMAScript 7 features, and one of them being ASYNC
and AWAIT
keywords/functions. These in conjunction do great wonders. I have started to replace some of my promises with async & await
. They seem to add great value to programming style.
Again, here is a pseudocode of how my async, await function looks like-
async function myAsyncFunction (myObj) {
var x = new MyDataStore(myObj);
return await x.init();
}
var returnVal = await myAsyncFunction(obj);
Keeping the syntax errors (if any) aside, both of them do the exact same thing is what I feel. I have almost been able to replace most of my promises with async,awaits.
Why is async,await needed when promises do a similar job?
Does async,await solve a bigger problem? Or was it just a different solution to callback hell?
As I said earlier, I am able to use promises and async,await to solve the same problem. Is there anything specific that async await solved?
Additional notes:
I have been using async,awaits and promises in my React projects and Node.js modules extensively. React especially have been an early bird and adopted a lot of ECMAScript 6 and ECMAScript 7 features.
Share Improve this question edited Sep 30, 2020 at 6:23 treedust 1423 silver badges13 bronze badges asked Dec 21, 2015 at 17:37 bozzmobbozzmob 12.6k17 gold badges51 silver badges73 bronze badges 6- 2 Your still trying to use async tools with synchronous functions - now in both code blocks. Why? – jfriend00 Commented Dec 22, 2015 at 4:52
- @jfriend00 Ok. Here I have my code gist.github.com/bozzmob/26d38b83dc37d1be37f5 . Please can you tell me what am I doing wrong? – bozzmob Commented Dec 22, 2015 at 4:58
- Where's an async operation in your code that is causing you to use anything other than regular synchronous code? – jfriend00 Commented Dec 22, 2015 at 5:13
- Please can you give me a pseudo code, so that I can know what I am doing wrong. Async operation meaning? – bozzmob Commented Dec 22, 2015 at 8:38
- 11 It sounds like you just need to do a bunch of reading to understand what async and await are for. Here are some articles: The long road to Async/Await in JavaScript and Simplifying Asynchronous Coding with ES7 Async Functions and Taming the asynchronous beast with ES7. – jfriend00 Commented Dec 22, 2015 at 17:36
6 Answers
Reset to default 105Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem?
async/await
simply gives you a synchronous feel to asynchronous code. It's a very elegant form of syntactical sugar.
For simple queries and data manipulation, Promises can be simple, but if you run into scenarios where there's complex data manipulation and whatnot involved, it's easier to understand what's going on if the code simply looks as though it's synchronous (to put it another way, syntax in and of itself is a form of "incidental complexity" that async/await
can get around).
If you're interested to know, you can use a library like co
(alongside generators) to give the same sort of feel. Things like this have been developed to solve the problem that async/await
ultimately solves (natively).
Async/Await provide a much nicer syntax in more complex scenarios. In particular, anything dealing with loops or certain other constructs like try
/catch
.
For example:
while (!value) {
const intermediate = await operation1();
value = await operation2(intermediate);
}
This example would be considerably more convoluted just using Promises.
Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem? or was it just a different solution to callback hell? As I said earlier, I am able to use Promises and Async,Await to solve the same problem. Is there anything specific that Async Await solved?
The first things you have to understand that async
/await
syntax is just syntactic sugar which is meant to augment promises. In fact the return value of an async
function is a promise. async
/await
syntax gives us the possibility of writing asynchronous in a synchronous manner. Here is an example:
Promise chaining:
function logFetch(url) {
return fetch(url)
.then(response => response.text())
.then(text => {
console.log(text);
}).catch(err => {
console.error('fetch failed', err);
});
}
Async
function:
async function logFetch(url) {
try {
const response = await fetch(url);
console.log(await response.text());
}
catch (err) {
console.log('fetch failed', err);
}
}
In the above example the await
waits for the promise (fetch(url)
) to be either resolved or rejected. If the promise is resolved the value is stored in the response
variable, and if the promise is rejected it would throw an error and thus enter the catch
block.
We can already see that using async
/await
might be more readable than promise chaining. This is especially true when the amount of promises which we are using increases. Both Promise chaining and async
/await
solve the problem of callback hell and which method you choose is matter of personal preference.
Async/await can help make your code cleaner and more readable in cases where you need complicated control flow. It also produces more debug-friendly code. And makes it possible to handle both synchronous and asynchronous errors with just try/catch
.
I recently wrote this post showing the advantages of async/await over promises in some common use cases with code examples: 6 Reasons Why JavaScript Async/Await Blows Promises Away (Tutorial)
await/async are often referred to as syntactic sugar to promises and let us wait for something (e.g. an API call), giving us the illusion that it is synchronous in an actual asynchronous code, which is a great benefit.
The things you want to achieve with async/await is possible with promises (but without the advantages of async/await). Lets take an example with this code:
const makeRequest = () => //promise way
getJSON()
.then(data => {
return data
})
makeRequest();
const makeRequest = async () => { //async await way
const data = await getJSON();
return data;
}
makeRequest()
Why is async/await prefered over promises?
Concise and clean - We don’t have to write
.then
and create an anonymous function to handle the response, or give a name data to a variable that we don’t need to use. We also avoided nesting our code. async/await is a lot cleaner.Error handling - Async/await makes it finally possible to handle both synchronous and asynchronous errors with the same try/catch format.
Debugging - A really good advantage when using async/await is that it’s much easier to debug than promises for 2 reasons: 1) you can’t set breakpoints in arrow functions that return expressions (no body). 2) if you set a breakpoint inside a
.then
block and use debug shortcuts like step-over, the debugger will not move to the following.then
because it only “steps” through synchronous code.Error stacks - The error stack returned from the promises chain gives us no idea of where the error occurred and can be misleading. async/await gives us the error stack from async/await points to the function that contains the error which is a really big advantage.
The only difference is the execution context between promise and async/await.
-When a Promise is created and the asynchronous operation is started, the code after the Promise creation continues to execute synchronously. -When the Promise is resolved or rejected, the attached callback function is added to the microtask queue (Priority queue). The microtask queue is processed after the current task has been completed but before the next task is processed from the task queue. -This means that any code that follows the creation of the Promise will execute before the callback function attached to the Promise is executed.
-On the other hand, with Async/Await, the await keyword causes the JavaScript engine to pause the execution of the async function until the Promise is resolved or rejected.
-While the async function waits for the Promise to resolve, it does not block the call stack, and any other synchronous code can be executed. Once the Promise is resolved, the execution of the async function resumes, and the result of the Promise is returned. If rejected, it throws an error value.
NOTES :
for async await :
- 'await' is only valid inside "async function" -> otherwise it will give syntax error.
- 'async function' always return promises, if value is not explicitly promises, it will implicitly wrapped in promises.
- async function are hoisted to top of their scope, and accessible througout that scope. [ can redeclare in certain context.]
for promises :
- '.then() function' returns new promise, different from original.
4 static methods for async task in promises :
- promise.all() : fulfill when all promise fulfill, reject when any promise rejects.
- promise.allSettled() : fulfill when all promises settle.
- promise.any() : fulfills when any fulfill, rejects when all reject.
- promise.race() : settle when any promise settles. [ fulfills when any promise fulfills, reject when any reject.]
本文标签: asynchronousWhat is the difference between JavaScript promises and async awaitStack Overflow
版权声明:本文标题:asynchronous - What is the difference between JavaScript promises and async await? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736833488a1954801.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论