• promise应用于ajax


    promise应用于ajax,可以在本页打开控制台,复制代码试验

    var url = 'https://www.cnblogs.com/mvc/blog/news.aspx?blogApp=dkplus';
    var url1 = 'https://www.cnblogs.com/mvc/blog/calendar.aspx?blogApp=dkplus&dateStr=';
    
    function getJSON(url) {
        return new Promise(function(resolve, reject) {
            var XHR = new XMLHttpRequest();
            XHR.open('GET', url, true);
            XHR.send();
    
            XHR.onreadystatechange = function() {
                if (XHR.readyState == 4) {
                    if (XHR.status == 200) {
                        try {
                            var response = XHR.responseText;
                            resolve(response);
                        } catch (e) {
                            reject(e);
                        }
                    } else {
                        reject(new Error(XHR.statusText));
                    }
                }
            }
        })
    }
    
    function renderAll() {
        return Promise.all([getJSON(url), getJSON(url1)]);
    }
    
    // 全部成功
    renderAll().then(function(value) {
        console.log(value);
    })
    
    
    function renderRace() {
        return Promise.race([getJSON(url), getJSON(url1)]);
    }
    
    // 有数据返回的时候
    renderRace().then(function(value) {
        console.log(value);
    })
    
  • 相关阅读:
    [紫书] 八数码问题(BFS)
    [紫书] 移动盒子(Boxes in a Line)
    [洛谷] P1803 凌乱的yyy / 线段覆盖 (贪心)
    [紫书] 破损的键盘(Broken Keyboard)
    bzoj3891
    poj3233
    bzoj1941
    Vijos2034
    poj2985
    Vijos1100
  • 原文地址:https://www.cnblogs.com/dkplus/p/9516437.html
Copyright © 2020-2023  润新知