Skip to content

实例方法 ​

本节目标:理解“实例方法”的核心思路,并能把它用于实际开发或面试表达。 实例方法 可以用then方法分别指定resolved状态和rejected状态的回调函数。 then方法可以接受两个回调函数作为参数。 第一个回调函数是Promise对象的状态变为resolved时调用; 第二个回调函数是Promise对象的状态变为rejected时调用。 其中,第二个函数是可选的。这两个函数都接受Promise对象传出的值作为参数。 promise.then( function (value) { // success }, function (error) { // failure } ); //


下面是一个`Promise`对象的简单例子。

function timeout(ms) { return new Promise((resolve, reject) => { setTimeout(resolve, ms, 'done'); }); } timeout(100).then((value) => { console.log(value); });

**实例**
异步加载图片
function loadImageAsync(url) {
    return new Promise(function (resolve, reject) {
        const image = new Image();
        image.onload = function () {
            resolve(image);
        };
        image.onerror = function () {
            reject(new Error('Could not load image at ' + url));
        };
        image.src = url;
    });
}
**Ajax**
const getJSON = function (url) {
    const promise = new Promise(function (resolve, reject) {
        const handler = function () {
            if (this.readyState !== 4) {
                return;
            }
            if (this.status === 200) {
                resolve(this.response);
            } else {
                reject(new Error(this.statusText));
            }
        };
        const client = new XMLHttpRequest();
        client.open("GET", url);
        client.onreadystatechange = handler;
        client.responseType = "json";
        client.setRequestHeader("Accept", "application/json");
        client.send();
    });
    return promise;
};
getJSON("/posts.json").then(function (json) {
    console.log('Contents: ' + json);
}, function (error) {
    console.error('出错了', error);
});
返回值:then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。
getJSON("/posts.json").then(function (json) {
    return json.post;
}).then(function (post) {
    // ...
});
**链式写法**
上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
采用链式的then,可以指定一组按照次序调用的回调函数。这时,前一个回调函数,有可能返回的还是一个Promise对象(即有异步操作),这时后一个回调函数,就会等待该Promise对象的状态发生变化,才会被调用。
getJSON("/post/1.json").then(function (post) {
    return getJSON(post.commentURL);
}).then(function (comments) {
    console.log("resolved: ", comments);
}, function (err) {
    console.log("rejected: ", err);
});

上面代码中,第一个then方法指定的回调函数,返回的是另一个Promise对象。这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。如果变为resolved,就调用第一个回调函数,如果状态变为rejected,就调用第二个回调函数。 如果采用箭头函数,上面的代码可以写得更简洁。 getJSON("/post/1.json").then( post => getJSON(post.commentURL) ).then( comments => console.log("resolved: ", comments), err => console.log("rejected: ", err) );

本站总访问 — 次