ajax异步场景的解决方案promise的用法

Promise是抽象异步处理对象以及对其进行各种操作的组件。

let promise = new Promise(function(resolve, reject) {

// 异步处理

// 处理结束后、调用resolve 或 reject

});

resolve(成功)时

reject(失败)时

let GetRequest= function(url, header)
{ 
   $.ajaxSettings.beforeSend = function(xhr,request){
       Object.keys(header).forEach(function(key){
            xhr.setRequestHeader(key,headers[key]);
       });
   };
   return url.map(function(item) {
        return new Promise((resolve, reject) => {
            $.ajax({
               url:item['url'],
               type: "POST",
               contentType: "application/x-www-form-urlencoded",
               dataType: "json",
               data:item['data']?item['data']:{},
               success: function (res) {
                    resolve(res.message)
               },
               error(e)
               {
                   reject(e.responseText)
                }
            })
        })
   });
}

let data = [
    {"url":'', "data":{}},
]
let header= {
'Accept':'application/vnd.app.v1+json',
'Authorization':'Bearer '+AccessToken
};
Promise.all(GetRequest(data,header)).then((result) => {

}).catch((error) => {

})
鲁ICP备16017569号-2