支付宝接口封装?
这是支付宝的获取定位的接口,我怎么把他封装一下,可以用anysc和await调用 ?
my.getLocation({ type: 1, // 获取经纬度和省市区县数据
success: (res) => {
console.log(res);
},
fail: (res) => {
my.alert({ title: '定位失败', content: JSON.stringify(res) });
},
complete: () => {},
});
回答:
function getLocation() { return new Promise((resolve, reject) => {
my.getLocation({
type: 1,
success: (res) => resolve(res),
fail: (error) => reject(error),
complete: () => { }
});
});
}
两种方式进行异步调用:
// 使用 async/await 进行异步操作(async function() {
try {
const loc = await getLocation();
console.log(loc);
} catch (err) {
console.error(err);
}
})();
// 使用 then 方法进行异步操作
getLocation().then(loc => {
console.log(loc);
}).catch(err => {
console.error(err);
});
回答:
const getLocationAsync = (params) => { return new Promise((resolve, reject) => {
my.getLocation({
...params,
success: (res) => resolve(res),
fail: (err) => reject(err)
});
});
}
try {
const res = await getLocationAsync({ type: 1 });
console.log(res);
} catch (err) {
my.alert({ title: '定位失败', content: JSON.stringify(res) });
}
如果想 Promise 化的函数比较多,还可以继续抽象:
const promisify = (func) => { return (params) => {
new Promise((resolve, reject) => {
func({
...params,
success: (res) => resolve(res),
fail: (err) => reject(err)
});
});
}
}
const getLocationAsync = promisify(my.getLocation);
const balabalaAsync = promisify(my.balabala);
const res1 = await getLocationAsync({ type: 1 });
const res2 = await balabalaAsync();
以上是 支付宝接口封装? 的全部内容, 来源链接: utcz.com/p/934377.html