Promise封装异步请求

  • 在小程序中对wx.request方法进行封装:
 http(param){
    return new Promise((resolve,reject)=>{
      try{
      wx.request({...param,success:function(data){
        resolve(data);
      },fail:function(){
        reject(new Exception("error"));
      }})
      }catch(e){
        reject(new Exception("error"));
      }
    })
  },

在实际调用的时候可以使用then方法调用

  this.http({
      url:'https://www.baidu.com'
    }).then((data)=>console.info(data)).then(()=>console.info("ok"))
  • jquery的异步请求(如get)请求已经默认返回promise
$.get("a.data").then((data)=>console.info(data)).then((d)=>console.info("ok"))
  • 也可以使用Promise再次封装:
function asynLoad(url) {
	return new Promise((resolve, reject) => {
		try {
			$.get(url, function(data) {
				resolve(data);
			});
		} catch (e) {
			reject(new Error("error"));
		}
	})
}

这样调用:

asynLoad("a.data").then((data) => console.info(data)).catch((error) => console.info(error));

不过看起来有点多此一举,因为jquery已经做过封装了。如果是其他框架未做过封装的,就可以采用此方法进行封装。

  • 更强大的是ES7里提供了async await这两个关键字

定义一个异步方法更多简单:

async function http(param) {
	let returnData = '';
	await $.get({ ...param,
		success: function(data) {
			returnData = data;
		}
	});
	 return returnData;
}

调用方法如下:

http({'url':'a.data'}).then((data=>console.info(data))).then((data)=>console.info("ok"));

这种方法是ES7中的新语法,应该是未来的一个趋势。使用起来非常容易阅读(要想学会可不容易)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值