Abstract: To exaggerate, the development of technology is the same as history. JS developers, embrace Async/Await!
- Making the warehouse: Fundebug/promise-asyncawait
More than six months ago, I was trumpeting 6 reasons Async/Await should replace Promise, and it seemed to attract some criticism. However, it’s only recently that I’ve really started to refactor the code, ditching promises in favor of full Async/Await. Because Node 8 is finally LTS!
Is Async/Await really better than Promise?
Yes, yes.
I’ve probably refactored about 1,000 lines of code these days, and the biggest feeling is that the code is much cleaner:
- Truly write asynchronous code synchronously
- Instead of writing then and its callbacks, you reduce the number of lines of code and avoid code nesting
- All asynchronous calls can be written in the same code block without defining redundant intermediate variables
- Async implicitly returns a Promise, so the variable can be returned directly without the Promise. Resolve conversion
Here is a very simple example to get a taste of Async/Await:
Example 1
const Promise = require("bluebird")
var readFile = Promise.promisify(require("fs").readFile)
/ / use the Promise
function usePromise()
{
let a
readFile("a.txt"."utf8")
.then(tmp= >
{
a = tmp
return readFile("b.txt"."utf8")
})
.then(b= >
{
let result = a + b
console.log(result) // Prints "Hello, Fundebug!"})}/ / use the Async/Await
async function useAsyncAwait()
{
let a = await readFile("a.txt"."utf8")
let b = await readFile("b.txt"."utf8")
let result = a + b
console.log(result) // Prints "Hello, Fundebug!"
}
usePromise()
useAsyncAwait()
Copy the code
As you can see from the examples, using Async/Await greatly simplifies the code, making it much more readable.
Is Async/Await really replacing Promise?
Yes, yes.
For the 6 reasons Async/Await replaces Promise, critics are clinging to the fact that Async/Await is implemented based on Promise and therefore replacement is inaccurate, which is a bit embarrassing.
On the one hand, what is replaced here is the way of writing asynchronous code, which is not to completely abandon the beloved Promise. Everyone on earth knows that Async/Await is based on Promise, so don’t be too sad. On the other hand, promises are implemented based on callback functions, so does Promise not replace callback functions?
After refactoring the code, I still used the Promise library bluebird. Talk is cheap, Show me the code!” Take a look at two examples.
Example 2: promise.promisify
Promisify methods that do not support promises using promise.promisify There are two ways to invoke asynchronous interfaces:
const Promise = require("bluebird")
var readFile = Promise.promisify(require("fs").readFile)
/ / use the Promise
function usePromise()
{
readFile("b.txt"."utf8")
.then(b= >
{
console.log(b)
})
}
/ / use the Async/Await
async function useAsyncAwait()
{
var b = await readFile("b.txt"."utf8")
console.log(b) / / output Fundebug! ""
}
usePromise()
useAsyncAwait()
Copy the code
FundebugFull stack JavaScript error monitoring platform, support a variety of front-end and back-end frameworks, can help you find bugs the first time!
Example 3: promise.map
Using promise.map to read data from multiple files, there are two ways to invoke the asynchronous interface:
const Promise = require("bluebird")
var readFile = Promise.promisify(require("fs").readFile)
var files = ["a.txt"."b.txt"]
/ / use the Promise
function usePromise()
{
Promise.map(files, file =>
{
return readFile(file, "utf8")
})
.then(results= >
{
console.log(results)
})
}
/ / use the Async/Await
async function useAsyncAwait()
{
var results = await Promise.map(files, file =>
{
return readFile(file, "utf8")})console.log(results)
}
usePromise()
useAsyncAwait()
Copy the code
Yes, I did use the Promise library, and readFile and Promise.map are both Promise functions. However, when calling readFile and promise. map, using Async/Await and using Promise are two different ways of writing, and they are interchangeable.
What’s wrong with Async/Await?
Yeah, yeah.
‘async’ should be added to the definition of a function that uses’ await ‘, and ‘await’ should be added to the definition of an asynchronous function that calls’ await ‘. This is annoying and sometimes easy to forget. If async code is not written, an error will be reported. If await code is not written, an error will occur.
Example 4
const Promise = require("bluebird")
var readFile = Promise.promisify(require("fs").readFile)
/ / not Async
function withoutAsync()
{
let b = await readFile("b.txt"."utf8") // error "SyntaxError: Unexpected identifier"
console.log(b)
}
/ / not await
async function withoutAwait()
{
let b = readFile("b.txt"."utf8")
console.log(b) / / print "Promise..."
}
withoutAsync()
withoutAwait()
Copy the code
Since Async/Await is a bit confusing, can we not write it? I think it will be possible in the future, as long as it can automatically recognize asynchronous code, which is probably the way forward. As for how to achieve that, I don’t know.
conclusion
The asynchronous way JavaScript is written, from callbacks to promises to Async/Await, is ostensibly just a change in writing, but essentially a layer upon layer abstraction, allowing us to implement the same functionality in simpler ways without the programmer having to worry about how the code is executed. In my opinion, this progress should not stop and one day we may not have to write Async/Await!
reference
- 6 reasons Async/Await should replace Promise
- Async/Await simplifies JavaScript code in this way
About Fundebug
Fundebug focuses on JavaScript, wechat applets, wechat mini games, Alipay applets, React Native, Node.js and Java real-time BUG monitoring. Since its official launch on November 11, 2016, Fundebug has handled more than 700 million error events in total, which has been recognized by many well-known users such as Google, 360, Kingsoft, and People’s Net. Welcome free trial!
Copyright statement
Reprint please indicate the author Fundebug and this article addresses: blog.fundebug.com/2017/12/13/…