理解JS中的Promise对象

时间:2020-07-29 15:18:44   收藏:0   阅读:82
  1. promise是异步编程的一种解决方法

promise对象代表一个异步操作,有三种状态,pending(进行中)、fulfilled(已成功)、rejected(已失败)
Promise对象是一个很神奇的东西, 究竟有哪些神奇呢?

  1. 怎么用

基本用法

instance = new Promise(function(resolve, reject){
           ...
           //when things goes right:
           resolve(value);
           ...
           //when things goes wrong:
           reject(error);
})

说明:

promise实例生成以后,可以用一个叫做then()方法来分别指定resolved状态和rejected状态的回调函数

instance.then( //注意, instance这个Promise对象默认向then中传入两个参数(分别是promise中的value&error), 在这里我们使用两个函数来进行处理

    function(value){
        process(value);
    }
    function(error){ // 可选
        process(error);
    }
)

说明:

promise实例生成以后,还有一个叫做catch()的方法来抛出错误异常.catch 其实是 .then(undefined, () => {}) 的语法糖

Promise 对象的错误具有"冒泡"性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个 catch 语句捕获。

getJSON("/post/1.json").then(function(post) {
  return getJSON(post.commentURL);
}).then(function(comments) {
  // some code
}).catch(function(error) {
  // 处理前两个回调函数的错误
});
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!