什么是异步?

说说你的理解,什么是异步。
由于各个语言处理异步的机制有差异,我们这里只说 JS 中的异步。

怎么样的代码是异步代码?

我们先不深入异步概念,先从「表象」来看看怎么样的代码是异步代码:

异步代码的书写顺序与执行顺序不同。(这并不是异步的定义。另外「书写顺序与执行顺序不同的代码」不一定是异步代码)

console.log(1)
setTimeout(function(){
  console.log(2)
},0)
console.log(3)

上面代码的书写顺序是 1 -> 2 -> 3;

但是执行顺序是 1 -> 3 -> 2。

中间的 console.log(2) 就是异步执行的。

你现在知道了「代码的书写顺序和执行顺序居然可以不同!」

什么是异步?

同步:一定要等任务执行完了,得到结果,才执行下一个任务。

function taskSync = function(){
  return '同步任务的返回值'
}

var result = taskSync() // 那么 result 就是同步任务的结果
otherTask()             // 然后执行下一个任务

异步:不等任务执行完,直接执行下一个任务。

function taskAsync = function(){
  var result = setTimeout(function(){
    console.log('异步任务的结果')
  }, 3000)
  return result
}

var result = taskAsync() // result 不是异步任务的结果,而是一个 timer id
otherTask()              // 立即执行其他任务,不等异步任务结束

聪明的你可能会发现,我们拿到的 result 不是异步执行的结果,而是一个 timer id,那么要怎么拿到异步任务的结果呢?

用回调。

改下代码如下:

function taskAsync = function(callback){
  var result = setTimeout(function(){
    callback('异步任务的结果')
  }, 3000)
  return result
}

taskAsync(function callback(result){
  console.log(result) // 三秒钟后,这个 callback 函数会被执行
})
otherTask()              // 立即执行其他任务,不等异步任务结束

所以「回调」经常用于获取「异步任务」的结果。

什么情况下需要用到异步?

现在有三个函数,taskA()、taskB() 和 taskC(),三个任务互不影响。
taskA 和 taskC 执行得很快,但是 taskB 执行需要 10 秒钟。

// 同步的写法
function taskB(){
  var response = $.ajax({
    url:"/data.json",
    async: false // 注意这里 async 为 false,表示是同步
  })
  return response // 十秒钟后,返回 response
}

taskA()
taskB()
taskC()

taskC 一定要等 taskB 执行完了才能执行,这就是同步。

执行顺序为:

A -> B -> AJAX 请求 -> C ---------------------------

现在换成异步:

// 异步的写法
function taskB(){
  var result = $.ajax({
    url:"/data.json",
    async: true // 异步
  })
  return result // 一定要注意,现在的 result 不是上面的 response
}
taskA()
taskB()
taskC()

这样写之后,执行顺序就是

A -> B -> C ---------------------------------------
       -> AJAX 请求 --------------------------------

就是说 AJAX 请求和任务C 同时执行。

但是请注意执行的主体。AJAX 请求是由浏览器的网络请求模块执行的,taskC 是由 JS 引擎执行的。

综上,如果几个任务互相独立,其中一个执行时间较长,那么一般就用异步地方式做这件事。

JS 引擎不能同时做两件事

有些人说异步是同时做两件事,但其实 JS 引擎不会这样。

以 setTimeout 为例,setTimeout 里面的代码一定会在当前环境中的任务执行完了「之后」才执行。

异步意味着不等待任务结束,并没有强制要求两个任务「同时」进行。

但是 AJAX 请求是可以与 JS 代码同时进行的,因为这个请求不是由 JS 引擎负责,而是由浏览器网络模块负责。

以上,就是异步的简介。

网络上对异步的解释很多,这里只是我的一己之见,如有疏漏,还望见谅。

作者:方应杭, 想学前端?进群

97 thoughts on “什么是异步?”

  1. Terrific article! That is the kind of info that should be shared across the web. Shame on Google for not positioning this post upper! Come on over and talk over with my web site . Thanks =)|

  2. I believe this is among the so much important information for me. And i’m glad reading your article. But should commentary on some general things, The site taste is wonderful, the articles is really nice : D. Good job, cheers|

  3. After looking into a handful of the articles on your website, I truly appreciate your technique of writing a blog. I added it to my bookmark webpage list and will be checking back soon. Take a look at my website as well and tell me your opinion.|

  4. Wow, marvelous blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is excellent, let alone the content!|

  5. Hey there! Do you use Twitter? I’d like to follow you if that would be ok. I’m definitely enjoying your blog and look forward to new updates.|

  6. Good day! I just would like to offer you a huge thumbs up for the excellent information you have here on this post. I will be coming back to your blog for more soon.|

  7. You are so interesting! I do not believe I’ve truly read a single thing like this before. So great to find another person with a few unique thoughts on this issue. Seriously.. thank you for starting this up. This web site is something that’s needed on the web, someone with a little originality!|

  8. Hi would you mind letting me know which hosting company you’re working with? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot faster then most. Can you suggest a good hosting provider at a fair price? Cheers, I appreciate it!|

  9. Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam responses? If so how do you protect against it, any plugin or anything you can advise? I get so much lately it’s driving me mad so any support is very much appreciated.|

  10. Ahaa, its pleasant conversation on the topic of this article at this place at this webpage, I have read all that, so at this time me also commenting at this place.|

  11. Hmm is anyone else encountering problems with the pictures on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any feed-back would be greatly appreciated.|

  12. My partner and I stumbled over here different page and thought I might as well check things out. I like what I see so now i am following you. Look forward to checking out your web page for a second time.|

  13. I have been surfing online more than 4 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my view, if all website owners and bloggers made good content as you did, the internet will be much more useful than ever before.|

  14. It’s a shame you don’t have a donate button! I’d without a doubt donate to this excellent blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this website with my Facebook group. Talk soon!|

  15. naturally like your web site but you have to check the spelling on several of your posts. A number of them are rife with spelling problems and I to find it very troublesome to inform the truth nevertheless I’ll definitely come again again.|

  16. I’m really enjoying the design and layout of your blog.
    It’s a very easy on the eyes which makes it much more enjoyable for me to
    come here and visit more often. Did you hire out a developer to create your theme?
    Great work!

  17. Good day very cool web site!! Man .. Beautiful .. Wonderful .. I will bookmark your website and take the feeds also? I am glad to find so many useful information right here in the put up, we’d like work out more strategies on this regard, thanks for sharing. . . . . .|

  18. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.|

  19. Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your webpage? My website is in the very same area of interest as yours and my visitors would certainly benefit from a lot of the information you provide here. Please let me know if this alright with you. Many thanks!|

  20. This design is wicked! You definitely know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Excellent job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!|

  21. Its like you read my mind! You seem to know so much about this, like
    you wrote the book in it or something. I think that you can do with some pics to
    drive the message home a bit, but instead of that, this
    is fantastic blog. A fantastic read. I’ll definitely be back.

  22. Hi, i feel that i noticed you visited my web site thus i came to go back the choose?.I am trying to find issues to improve my website!I guess its ok to use some of your ideas!!|

  23. You are so cool! I don’t believe I’ve read something like this before. So great to discover someone with genuine thoughts on this issue. Really.. thank you for starting this up. This site is one thing that is needed on the web, someone with a bit of originality!|

  24. That is very fascinating, You’re an overly skilled blogger. I’ve joined your feed and sit up for in quest of more of your wonderful post. Also, I have shared your website in my social networks|

  25. I wanted to thank you for this very good read!! I definitely loved every bit of it. I have you saved as a favorite to check out new things you post…|

  26. My brother recommended I may like this website. He used to be totally right. This put up actually made my day. You cann’t consider simply how much time I had spent for this information! Thank you!|

  27. magnificent issues altogether, you simply received a emblem new reader. What would you suggest about your put up that you simply made some days ago? Any certain?

  28. Thank you for the auspicious writeup. It in reality was once a leisure account it. Look complex to more brought agreeable from you! By the way, how could we communicate?

  29. I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this best doc.

  30. As I web-site possessor I believe the content material here is rattling fantastic , appreciate it for your efforts. You should keep it up forever! Best of luck.

  31. Very well written story. It will be useful to anybody who employess it, as well as yours truly :). Keep doing what you are doing – i will definitely read more posts.

  32. Very nice post. I just stumbled upon your blog and wanted to say that I’ve truly enjoyed surfing around your blog posts. After all I will be subscribing to your feed and I am hoping you write again very soon!

  33. I will right away take hold of your rss feed as I can not to find your e-mail subscription link or newsletter service. Do you have any? Kindly let me understand in order that I may just subscribe. Thanks.|

  34. Hello very cool site!! Man .. Beautiful .. Amazing .. I’ll bookmark your web site and take the feeds also…I am happy to seek out numerous helpful info here in the post, we need work out extra techniques in this regard, thanks for sharing.

  35. I feel this is among the such a lot vital info for me. And i am happy studying your article. However should statement on some basic issues, The website taste is ideal, the articles is in point of fact nice :D. Just right process, cheers.

  36. Hello my loved one! I wish to say that this article is awesome, nice written and come with approximately all significant infos. I’d like to look extra posts like this.

  37. An intriguing discussion is definitely worth comment. I think that you should publish more about this subject matter, it might not be a taboo subject but typically people do not talk about these subjects. To the next! All the best!!|

  38. I really like what you guys are up too. This type of clever work and reporting! Keep up the fantastic works guys I’ve included you guys to my own blogroll.|

发表评论

电子邮件地址不会被公开。