Promise 是什么?

window.Promise 已经是 JS 的一个内置对象了。

  1. Promise 有规格文档吗?
  2. 你一般如何使用 Promise。

目前的 Promise 都遵循 Promises/A+ 规范。

英文规范:https://promisesaplus.com/

中文翻译:图灵社区 : 阅读 : 【翻译】Promises/A+规范

看完规范你可以了解 Promise 的全貌,本文主要讲讲 Promise 的用途。

Promise 之前的时代——回调时代

假设我们用 getUser 来说去用户数据,它接收两个回调 sucessCallback 和 errorCallback:

function getUser(successCallback, errorCallback){
  $.ajax({
    url:'/user',
    success: function(response){
      successCallback(response)
    },
    error: function(xhr){
      errorCallback(xhr)  
    }
  })
}

看起来还不算复杂。

如果我们获取用户数据之后还要获取分组数组、分组详情等,代码就会是这样:

getUser(function(response){
    getGroup(response.id, function(group){
      getDetails(groupd.id, function(details){
        console.log(details)
      },function(){
        alert('获取分组详情失败')
      })
    }, function(){
      alert('获取分组失败')
    })
  }, function(){
  alert('获取用户信息失败')
})

三层回调,如果再多一点嵌套,就是「回调地狱」了。

Promise 来了

Promise 的思路呢,就是 getUser 返回一个对象,你往这个对象上挂回调:

var promise = getUser()
promise.then(successCallback, errorCallback)

当用户信息加载完毕,successCallback 和 errorCallback 之一就会被执行。

把上面两句话合并成一句就是这样的:

getUser().then(successCallback, errorCallback)

如果你想在用户信息获取结束后做更多事,可以继续 .then:

getUser().then(success1).then(success2).then(success3)

请求成功后,会依次执行 success1、success2 和 success3。

如果要获取分组信息:

getUser().then(function(response){
  getGroup(response.id).then(function(group){
    getDetails(group.id).then(function(){

    },error3)
  },error2)
}, error1)

这种 Promise 写法跟前面的回调看起来其实变化不大。

真的,Promise 并不能消灭回调地狱,但是它可以使回调变得可控。你对比下面两个写法就知道了。

getGroup(response.id, success2, error2)

getGroup(response.id).then(success2, error2)

用 Promise 之前,你不能确定 success2 是第几个参数;

用 Promise 之后,所有的回调都是

.then(success, error) 

这样的形式。

以上是 Promise 的简介,想完整了解 Promise,请参考下面的自学链接。

Promise对象 — JavaScript 标准参考教程(alpha)

作者:方应杭

48 thoughts on “Promise 是什么?”

  1. What i do not understood is if truth be told how you’re not actually a lot more well-favored than you may be now. You’re so intelligent. You understand therefore significantly when it comes to this matter, made me for my part consider it from so many various angles. Its like women and men aren’t interested until it’s something to accomplish with Lady gaga! Your own stuffs excellent. At all times deal with it up!|

  2. Hi there, just became alert to your blog through Google, and found that it is truly informative. I am going to watch out for brussels. I’ll be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!|

  3. Fantastic goods from you, man. I’ve remember your stuff prior to and you’re simply too great. I really like what you have received here, really like what you are saying and the way by which you say it. You are making it entertaining and you still take care of to keep it wise. I cant wait to read much more from you. This is really a wonderful web site.|

  4. Howdy would you mind letting me know which webhost you’re utilizing? I’ve loaded your blog in 3 different browsers and I must say this blog loads a lot quicker then most. Can you suggest a good hosting provider at a fair price? Kudos, I appreciate it!|

  5. It is appropriate time to make some plans for the longer term and it is time to be happy. I’ve read this post and if I may I want to suggest you some interesting issues or tips. Perhaps you can write subsequent articles referring to this article. I desire to read more issues about it!|

  6. I am genuinely happy to glance at this website posts which carries tons of useful data, thanks for providing these information.|

  7. Woah! I’m really loving the template/theme of this site. It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between superb usability and visual appearance. I must say you have done a awesome job with this. Additionally, the blog loads very fast for me on Chrome. Superb Blog!|

  8. Hello there! I could have sworn I’ve visited your blog before but after going through many of the posts I realized it’s new to me. Anyways, I’m certainly happy I discovered it and I’ll be bookmarking it and checking back regularly!|

  9. I am curious to find out what blog platform you’re using? I’m experiencing some minor security problems with my latest website and I’d like to find something more safeguarded. Do you have any recommendations?|

  10. Howdy would you mind letting me know which web host you’re using? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot quicker then most. Can you suggest a good web hosting provider at a reasonable price? Thanks, I appreciate it!|

  11. Hi! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Kudos!|

  12. After looking into a number of the articles on your website, I truly appreciate your technique of writing a blog. I saved it to my bookmark site list and will be checking back in the near future. Please check out my web site too and let me know what you think.|

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

  14. Hi there, You’ve performed a great job. I’ll definitely digg it and personally recommend to my friends. I’m sure they will be benefited from this website.|

  15. Hi! I’m at work browsing your blog from my new iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the superb work!|

  16. I don’t even know the way I stopped up here, however I thought this post used to be good. I don’t realize who you might be however definitely you are going to a famous blogger in the event you aren’t already. Cheers!|

  17. First of all I want to say terrific blog! I had a quick question that I’d like to ask if you don’t mind. I was interested to know how you center yourself and clear your head prior to writing. I’ve had difficulty clearing my mind in getting my ideas out there. I do enjoy writing however it just seems like the first 10 to 15 minutes are usually lost just trying to figure out how to begin. Any ideas or hints? Thanks!|

  18. I will right away grasp your rss feed as I can’t in finding your e-mail subscription link or newsletter service. Do you have any? Kindly let me understand so that I could subscribe. Thanks.|

  19. whoah this blog is great i really like reading your posts. Stay up the great work! You recognize, a lot of persons are looking around for this information, you can aid them greatly. |

  20. Please let me know if you’re looking for a writer for your site. You have some really good articles and I feel I would be a good asset. If you ever want to take some of the load off, I’d really like to write some content for your blog in exchange for a link back to mine. Please shoot me an email if interested. Cheers!|

  21. I every time used to read paragraph in news papers but now as I am a user of web so from now I am using net for content, thanks to web.|

  22. You are so cool! I don’t believe I’ve read through a single thing like that before. So wonderful to discover someone with original thoughts on this issue. Really.. thanks for starting this up. This website is something that is needed on the web, someone with some originality!|

发表评论

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