首页 > 解决方案 > Javascript 链接承诺

问题描述

我需要返回一个包含对象的承诺。我已经尝试过了,但我不确定这是否是正确的方法?

export const getCurrentLocation = async () => {
  const currentLoc = {
    code: null,
    position: null,
    watchId: null,
  };

  const promise = new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        currentLoc.code = 200;
        currentLoc.position = position;

        resolve(currentLoc);
      },
      (error) => {
        console.log('Postion==err===>', error);
        currentLoc.code = 400;
        reject(currentLoc);
      },
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
    );
  }).then(
    new Promise((resolve, reject) => {
      const watchId = navigator.geolocation.watchPosition();
      currentLoc.watchId = watchId;
      resolve(currentLoc);
    }),
  );

  return promise;
};

在 Promise 块内我有异步功能

标签: javascriptpromise

解决方案


您可以使用async/await

const obj = {};
const populate = async() => {
  await (() => obj.value1 = 'Deepak')();
  await (() => obj.value2 = 'JavaScript')();
  console.log(obj);
};
populate();


推荐阅读