zoukankan      html  css  js  c++  java
  • promise对象

    直接放大佬写的:https://es6.ruanyifeng.com/#docs/promise

    这边写一下怎么用promise去封装请求

    var urla =  'http://api.xuandan.com/DataApi/index?AppKey=3aw4643qpb&page=1&cid=';
        var de = '请求失败';
        var ajax = function(url){
          return   new Promise(function(resolve,reject){
                    var xhr = new XMLHttpRequest();

                    xhr.open('get',url);
                    xhr.send();

                    xhr.onreadystatechange = function(){
                        if(xhr.readyState == 4 && xhr.status == 200){
                            var res = JSON.parse(xhr.responseText);
                            resolve(res)

                        }else if(xhr.readyState !== 4 && xhr.status !== 200){
                            reject(de)
                        }
                    }


            })
        }

        ajax(urla).then(res => {
            console.log(res);
        }).catch(error =>{
            console.log(error);
        })
     
     
     
     
     
  • 相关阅读:
    WebView用法与JS交互(2) 响应webview中的图片点击事件
    出栈序列(栈和队列)
    Log Files
    Mr. Frog’s Game
    Comparison of Android versions
    Linearization of the kernel functions in SVM
    Game of Nuts
    Easy Summation
    Automatic Judge
    Coprime Sequence
  • 原文地址:https://www.cnblogs.com/chenyudi/p/12392273.html
Copyright © 2011-2022 走看看