前端开发

Promise 与异步编程

2018-03-13  本文已影响0人  WestLonely
JS引擎工作流程

2. Promise的基础知识

2.1 Promise生命周期

graph TD
A[padding] --> B[Fulfilled]
A[padding] --> C[Rejected]
let ajaxPromise = (url, params) => {
    // 判断 params 是否存在
    if(params) {
        url = url + '?' + params;
    }
    return new Promise ((resolve, reject) => {
        let ajax = null;
        if(window.XMLHttpRequest) {
            ajax = new XMLHttpRequest ();
        }
        else {
            ajax = new ActiveXObject ('Microsoft.XMLHTTP ');
        }
        ajax.open ('GET', url);
        ajax.send ();
        ajax.onreadystatechange = () => {
            if(ajax.readyState == 4 && ajax.status == 200) {
                resolve (ajax.responseText);
            }
        };
        // 如果 3秒内请求未完成,则调用 失败函数
        setTimeout (() => {
            reject ();
        }, 3000);
     
    });
};
let url = 'http://192.168.2.220:8080';
let params = 'name=wangjq&handsome=true';
ajaxPromise(url,params).then(result=>{
    console.log (result.data);
},reason => {
    console.log (reason.message);
})

上一篇下一篇

猜你喜欢

热点阅读