支付宝接口封装?

这是支付宝的获取定位的接口,我怎么把他封装一下,可以用anysc和await调用 ?

my.getLocation({
  type: 1, // 获取经纬度和省市区县数据
  success: (res) => {
    console.log(res);
  },
  fail: (res) => {
    my.alert({ title: '定位失败', content: JSON.stringify(res) });
  },
  complete: () => {},
});
阅读 1.8k
2 个回答
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();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题