React Native 我正在写一个递归函数,必须等待函数完成,使用async/await,我怎样才能正确地做到这一点?

qgelzfjb  于 2022-12-14  发布在  React
关注(0)|答案(1)|浏览(129)

我想做一个递归函数,它会一直等到值距离更新。

`  const calculateDistance = async() => {
    const loc = await Location.getCurrentPositionAsync({enableHighAccuracy: true})
    const distanceCalc = await getPreciseDistance(
      {latitude: 51.493280, longitude: 4.294605 },
      {latitude: loc.coords.latitude, longitude: loc.coords.longitude})
      await SetDistance(distanceCalc)
      calculateDistance();
      return true
    }`

我尝试创建第二个函数来等待函数完成,如下所示:

const calculateDistance = (loc) => {
const distanceCalc =  getPreciseDistance(
  {latitude: 51.493280, longitude: 4.294605 },
  {latitude: loc.coords.latitude, longitude: loc.coords.longitude})
  SetDistance(distanceCalc)
  return true
}
const calculateDistance1 = async() => {
  const loc = await Location.getCurrentPositionAsync({enableHighAccuracy: true})
  const truet = await calculateDistance(loc);
  calculateDistance1();
}

然后重复这个函数,但没有起作用。我还尝试用if语句来解决它,当函数完成时,这些语句会被更改。我得到的错误是“可能的未处理承诺拒绝(id:2)”,也有flushedQueu。

pobjuy32

pobjuy321#

1.将promise对象返回给调用示例
1.需要一些循环中断子句
示例代码演示了您可能需要实现的目标:

let idx = 0;

const calculateDistance = async () => {
  console.debug(`calculateDistance iteration ${idx}`);

  // ... your code

  idx++;
  if (idx < 5) {
    return calculateDistance();
  } else {
    return Promise.resolve();
  }
};

console.debug("starting");
calculateDistance().then(() => {
  console.debug("done");
});

相关问题