es6 --- > promise.prototype.then的链式引用

本文介绍如何使用Promise的链式调用进行Ajax请求,通过封装getJSON方法,实现异步读取数据后再进行下一步Ajax操作,展示了使用箭头函数简化代码的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多时候,我们需要使用ajax请求获取数据A.并使用A中的数据A.a来进行下一步的Ajax操作…
下面使用promise.prototype.then的链式引用来实现

// 首先封装一个getJSON的方法.
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 !== 4) {
                return;
            }
            if (this.status === 200) {
                resolve(this.response);
            } else {
                reject(new Error(this.statuText));
            }
        };
    });
    return promise;
}

// 上面函数调用.getJSON(url)即可, 使用.then可以改变Resolved状态的回调函数
// 链式调用如下:
getJSON("post/1.json").then(function(post) {
    return getJSON(post.commentURL);
}).then(function funcA(comments) {
    console.log("Resolved: ", comments);
},  function funcB(err) {
    console.log("Rejected: ", err);
});

// 注:首先,调用getJSON异步读取post/1.json路径下的数据
// 读取结果作为参数放在post里面,然后再调用getJSON函数,参数为post.commentURL,读取post.commentURL路径的数据
// 若读取成功执行,函数funcA,否则执行函数funcB....

// 下面尝试使用箭头函数重写链式调用,,,
getJSON("post/1.json").then(
    post => getJSON(post.commentURL)
).then(
    comments => console.log("Resolved: ", comments),
    err => console.log("Rejected: ", err)
);

// 简洁明了,这个接口还不错...

参考《ES6标准入门》(第3版) P276、P279

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值