可以与获取轮询异步直到满足条件吗? (幸免于难)

can async with fetch poll until a condition is met? (survive rejection)

使用 fetch API 和 async/await,是否可以无限期地继续轮询,而不管 URL 是否可用?我预计 URL 最终可能会可用,因此我想继续尝试直到满足条件。试图提出一个最小的可行代码示例,但我不确定我是否成功了:

// this is just a placeholder. It will eventually be a function 
// that evaluates something real. 
// Assume validContinue gets updated elsewhere.      
function shouldContinue() {
    return validContinue;
}
      
async function wonderPoll(someUrl) {

  // just a delay mechanism
  function wait(ms = 1000) {
    return new Promise(resolve => {
      setTimeout(resolve, ms);
    });
  }

  // the actual individual poll
  async function pollingFunction(url) {

    const response = await fetch(url, {
      cache: 'no-store'
    });

    if (response.ok) {
      return response;
    } else {
      Promise.reject(response);
    }

  }

  // allegedly keep polling until condition is met. 
  // But the rejected Promise is breaking out!
  while (shouldContinue()) {
    await wait();
    result = await pollingFunction(someUrl);
  }
  
  // when the fetch hits a rejected state, we never get here!
  console.log('done with the while loop, returning last successful result')

  return result;
}

const sampleUrl = 'https://get.geojs.io/v1/ip/country.json?ip=8.8.8.8';
const sampleUrl2 = 'http://totallybroken_fo_sho';

// swap the URL to test
wonderPoll(sampleUrl)
  .then((result) => {
    console.log('got a result', result)
  })
  .catch((err) => {
    console.log('got an error', err)
  });

我明白发生了什么(我认为)。父调用最终执行轮询函数,该函数拒绝 Promise。 continue的条件理论上还是满足的,但是rejection跳出了While循环,直接向上发送到rejection。这会一直传播到 original/initial Promise 的 catch 方法。在已解决的 Promises 的情况下,它甚至不会命中 While 循环之后的任何代码。

我不知道如何防止这种情况发生。我想我不明白拦截和解决承诺的语法。当我用 Promise.resolve(response) 替换响应解析器中的 Promise.reject 时,它仍然最终拒绝到顶部。

如果我提供的URL有效,会一直持续到不再满足条件。


这里是 fiddle:https://jsfiddle.net/gregpettit/qf495bjm/5/

要使用 fiddle,“停止”按钮模拟满足的条件,我提供了两个不同的 URLs,它们必须手动交换(通过传递 someUrl 或 someUrl2 ) 进行测试。

预期结果:

实际结果:

你可以try…catch它来防止跳出循环。

while (shouldContinue()) {
  try {
    await wait();
    result = await pollingFunction(someUrl);
  } catch (e) {}
}

两件事

 } else {
            Promise.reject(response);
        }

应该return那个。它现在“意外地”工作。

 } else {
            return Promise.reject(response);
        }

其次,result = await pollingFunction(someUrl); 可能想要向其中添加 .catch: result = await pollingFunction(someUrl).catch(_=>null); 或任何可以在封闭的 while

中测试的内容

但我认为你可以这样简化整个事情:

export async function wonderPoll(someUrl) {
    while (shouldContinue()) {
        await wait();

        const response = await fetch(someUrl, { cache: 'no-store' });

        if (response.ok)
            return response;
    }
    return Promise.reject(); // only if !shouldContinue()
}

将 while 循环中的代码更改为 try/catch 以便捕获错误

result 可以在没有错误的时候保存一个值,或者在有错误的时候保存一个原因

循环停止后,您要么 return 值,要么抛出原因

如下

async function wonderPoll(someUrl) {

  // just a delay mechanism
  function wait(ms = 1000) {
    return new Promise(resolve => {
      setTimeout(resolve, ms);
    });
  }

  // the actual individual poll
  async function pollingFunction(url) {

    const response = await fetch(url, {
      cache: 'no-store'
    });

    if (response.ok) {
      return response;
    } else {
      Promise.reject(response);
    }

  }

  // allegedly keep polling until condition is met. But the rejected Promise is breaking out!
  while (shouldContinue()) {
    try {
      await wait();
      const value = await pollingFunction(someUrl);
      result = {value};
    } catch (reason) {
      result = {reason};
    }
  }
  // when the fetch hits a rejected state, we never get here!
  console.log('done with the while loop, returning last successful result')
  if (result.reason) {
    throw result.reason;
  }
  return result.value;
}

运行 示例 https://jsfiddle.net/twkbo9pg/

该示例在结果中包含 status,但这是不必要的(我从我的 Promise.allSettled polyfill 中借用了代码,但忘记删除 属性)

您可能想查看可观察的流!如果随着时间的推移,你会收到大量数据,这就是 rxjs 的全部。

如果这感觉很糟糕(有点像哈哈),实际上有几种方法可以做到这一点。

import { ajax } from "rxjs/ajax";
import { duration } from "moment-timezone"; // I copied this from some old code... whatever.
import { catchError, map, share, switchMap } from "rxjs/operators";

const baseUrl = "http://foo.bar"
const base = (method, headers = {}) => ({
  method,
  headers: {
    Accept: "application/json",
    ...headers,
  },
  crossDomain: true,
  withCredentials: true,
})

const ajaxGet = url => ajax({ ...base("GET"), url })

export const userEpic = timer(0, duration(5, "minutes").asMilliseconds()).pipe(
  switchMap(() =>
    ajaxGet(`${baseUrl}/users`).pipe(
      map(({ response }) => getUsersSuccess(response)),
      catchError(e => of(getUsersError(e))),
    )
  ),
  share()
)