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去捕获异常。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容