回调函数转换为promise

1,124 阅读1分钟

在使用async时必须将回调函数转为promise, 虽然原生的函数执行结果是一个promise对象 , 但是这个promise对象的reject时和resolved时传入参数与回调函数success和fail传入的参数不同 , 为了保证不出现奇奇怪怪的 , 未在文档中描述的参数 ,我们还是自己封装为妙 .

function becomePromise(api, object , failMessage) {
    //failMessage主要是为了方便捕获不同的错误~
	return new Promise(function(resolve, reject) {
		object.success = (res) => resolve(res);
		object.fail = (res) => reject(!failMessage ? res : [res,failMessage]);
		api(object);
	})
}

之前几十行的代码瞬间变成十行左右,舒服了~~ asyncawait超级香 !

//获取背景图片的一个业务
try{
				const {tempFilePaths: [path]} = await becomePromise(uni.chooseImage,{count: 1},'chooseImage');
				const {savedFilePath:newPath} = await becomePromise(uni.saveFile,{tempFilePath:path},'saveFile');
				const backgroundImage = this.$commonFun.getStorageSync('backgroundImage','');
				if(backgroundImage!='') uni.removeStorageSync(backgroundImage);
				await becomePromise(uni.setStorage,{key: 'backgroundImage',data: newPath},'setStorage');
				this.setBackground(newPath);
			}catch(e){
				if(e[1] == 'chooseImage') this.fail('系统不支持选择图片');
				else if(e[1] == 'saveFile') this.fail('保存图片失败');
				else if(e[1] == 'setStorage') this.fail('保存图片路径失败,请清除缓存');
			}