美文网首页
promise 解决回调地狱。

promise 解决回调地狱。

作者: 一洼世界 | 来源:发表于2017-11-04 21:55 被阅读219次
  1. ES6的promise的语言标准。promise/A+规范
    2.如何使用
    3.场景。

promiseObj.then(onFulfilled,onRejected);

onFulfilled=function(value){
return promiseObj2
}
onRejected=function(err){}

简单理解例子:

var getJSON = function (url) {
    var promise = new Promise(function (resolve, reject) {
        function handler() {
            if (this.state === 200) {
                resolve(this.response);
            } else {
                reject(new Error(this.statusText));
            }
        }
    });
    return promise;
};
//场景一
getJSON('/posts.json').then(function (json) {
    console.log('Content' + json);
}, function (error) {
    console.error('error');
});

//场景二
getJSON('/posts.json').then(function (json) {
    return json.post;
}).then(function (post) {

});

//场景三
getJSON('/posts.json').then(
    post => getJSON(post.commentURL)
).then(
    comments => console.log('comments'),
    err => console.log('rejected', err)
    );

getJSON('/posts.json').then(function (post) {
    getJSON(post.commentURL);
    }
).then(function(comments){
    console.log();
},function(err){
    console.err();
});

//catch 最好用catch去捕获异常。

相关文章

网友评论

      本文标题:promise 解决回调地狱。

      本文链接:https://www.haomeiwen.com/subject/beqvsttx.html