Promise构造函数接收一个函数作为参数,该函数的两个参数分别是resolve方法和reject方法。如果异步操作成功,则用resolve方法将Promise对象的状态变为"成功"(即从pending变为resolved); 如果异步操作失败,则用reject方法将状态变为"失败"(即从pending变为rejected).

var getJSON = function(url) {
    var promise = new promise(function (resolve, reject) {
        var client = new XMLHttpRequest();
        client.open('GET', url);
        client.onreadystatechange = handler;
        client.responseType = 'json';
        client.setRequestHeader('Accept', 'application/json');
        client.send();

        function handler() {
            if (this.readyState === this.DONE) {
                if (this.status === 200) {
                    resolve(this.response);
                }
                else {
                    reject(this);
                }
            }
        }
    });

    return promise;
};

getJSON('/posts.json').then(function (json) {
    // continue
}, function (error) {
    // handle errors
});

小渝人儿
1.1k 声望850 粉丝

前端工程师