promise 解决回调地狱。

  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 解决回调地狱。)