The usage of async and await in Vue

Ichiro Qiu Shan 2020-11-13 02:57:22
usage async await vue

But first, let me say async Usage of , It's put in front of the function as a keyword , Used to indicate that a function is an asynchronous function , because async It means asynchronous , Asynchronous function means that the execution of the function will not block the execution of the following code . Write a async function

async function timeout() {

return 'hello world';

The grammar is very simple , It's just adding... Before the function async keyword , To show that it's asynchronous , So how do we call it ?async Functions are also functions , We usually use functions as we like , Just call it with parentheses , To show that it doesn't block the execution of the code behind it , We are async Add a sentence after the function call console.log;

async function timeout() {

return 'hello world'
console.log(' Although in the back , But I'll do it first ');

Open the browser console , We see that
 Insert picture description here
async function timeout Called , But there's no output , It's not supposed to return ‘hello world’, Don't worry , Have a look timeout() What does the execution return ? Put the above timeout() Change statement to console.log(timeout())

async function timeout() {

return 'hello world'
console.log(' Although in the back , But I'll do it first ');

Keep looking at the console
 Insert picture description here
original async The function returns a promise object , If you want to get promise Return value , We should use then Method , Continue to modify the code

async function timeout() {

return 'hello world'
timeout().then(result => {

console.log(' Although in the back , But I'll do it first ');

Look at the console
 Insert picture description here
We've got "hello world’, meanwhile timeout There is no blocking in the execution of the following code , and What we said just now is the same .

At this time , You may have noticed in the console Promise There is one resolved, This is a async The implementation principle inside the function . If async Function returns a value , When this function is called , Internally it will call Promise.solve() Method to turn it into a promise Object as return , But if timeout Error thrown inside the function ? Then it will call Promise.reject() Return to one promise object , At this time, make a revision timeout function

async function timeout(flag) {

if (flag) {

return 'hello world'
} else {

throw 'my god, failure'
console.log(timeout(true)) // call Promise.resolve() return promise object .
console.log(timeout(false)); // call Promise.reject() return promise object .

The console is as follows :
 Insert picture description here
If an error is thrown inside a function , promise The object has a catch Method to capture .

timeout(false).catch(err => {


async The key words are almost the same , Let's think about await keyword ,await It means waiting , So what does it wait for , What's behind it ? In fact, it can be followed by any expression , But we're going to put one back promise The expression of the object . Be careful await Keywords can only be put in async In the function

Now write a function , Let it go back to promise object , The function is to 2s And then multiply the number by 2
// 2s Then return double the value

function doubleAfter2seconds(num) {

return new Promise((resolve, reject) => {

setTimeout(() => {

resolve(2 * num)
}, 2000);
} )

Now write another async function , So that you can use await keyword , await What's on the back is back promise An expression of an object , So it can be written after it doubleAfter2seconds Function call

async function testResult() {

let result = await doubleAfter2seconds(30);

Open console ,2s after , Output 60.

Now let's look at the execution of the code , call testResult function , It encountered await, await Wait a minute , The code pauses here , No more downward execution , What is it waiting for ? Wait for the next one promise Finished executing object , And then to get promise resolve And return , After getting the return value , It continues to go down . Specific to the Our code , encounter await after , The code is suspended , wait for doubleAfter2seconds(30) completion of enforcement ,doubleAfter2seconds(30) Back to promise Start execution ,2 second after ,promise resolve 了 , And return the value of 60, At this time await To get the return value 60, And then assign it to result, The end of the pause , The code just starts to execute , perform console.log sentence .

Just this one function , We may not see async/await The role of , If we want to calculate 3 The value of the number , Then output the obtained value ?

async function testResult() {

let first = await doubleAfter2seconds(30);
let second = await doubleAfter2seconds(50);
let third = await doubleAfter2seconds(30);
console.log(first + second + third);

6 Seconds later , Console output 220, We can see , Writing asynchronous code is like writing synchronous code , There's no more pullback zones .

Be careful :

async and await be based on promise Of . Use async Will always return a promise object . This is important , Remember , This may be a mistake prone place you come across .
In the use of await When we pause the function , Not the whole code .
async and await It's non blocking .
You can still use Promise for example Promise.all().

本文为[Ichiro Qiu Shan]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple