Estoy sondeando mi informe agregando un intervalo de 5 segundos entre cada solicitud.
const addDelay = timeout => new Promise(resolve => setTimeout(resolve, timeout)) export const myReport = () => async (dispatch) => { dispatch({ type: constants.DOWNLOAD_REPORT_REQUEST }) let url = `/admin/dashboard/report.js?project_id=${projectId}&tool_id=${toolId}` try { const subscribe = async (uri) => { let response = await fetch(uri, { method: 'GET', headers: { 'content-type': 'application/json', 'x-api-token': `Bearer ${token}` } }) const resBody = await response.json() if (resBody.status === 'success') { window.location.href = resBody.url dispatch({ type: constants.DOWNLOAD_REPORT_SUCCESS }) } else { await addDelay(5000) await subscribe(url) // return; // setTimeout(() => { // dispatch({ // type: constants.SHOW_DOWNLOAD_POPUP // }) // return; // }, 15000); } } subscribe(url) } catch (error) { dispatch({ type: constants.DOWNLOAD_REPORT_FAILURE, errorMessage: error.status }) } }Ahora, aquí quiero detener el sondeo después de 15 segundos y mostrar una ventana emergente.
El problema es que no puedo agregar setTimeout aquí porque estoy usando async . Además, no dejará de llamar al método de subscribe una y otra vez, ya que sigue entrando en otra parte, el return no funciona.
Quiero salir de otra parte, dejar de llamar a la función y mostrar una ventana emergente después de 15 segundos. ¿Cómo logro esto?
Es posible que su declaración de devolución no funcione porque esta función es recursiva : nunca llegará allí si la búsqueda sigue fallando. ¿Qué hay de simplemente agregar un índice para rastrear cuántas veces has vuelto a intentar suscribirte?
const addDelay = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout)); const failed = 0; export const myReport = () => async (dispatch) => { dispatch({ type: constants.DOWNLOAD_REPORT_REQUEST, }); let url = `/admin/dashboard/report.js?project_id=${projectId}&tool_id=${toolId}`; try { const subscribe = async (uri) => { let response = await fetch(uri, { method: 'GET', headers: { 'content-type': 'application/json', 'x-api-token': `Bearer ${token}`, }, }); const resBody = await response.json(); if (resBody.status === 'success') { window.location.href = resBody.url; dispatch({ type: constants.DOWNLOAD_REPORT_SUCCESS }); } else { if (failed >= 3) { // whatever you want to do on fail } else { failed += 1; await addDelay(5000); await subscribe(url); } } }; subscribe(url); } catch (error) { dispatch({ type: constants.DOWNLOAD_REPORT_FAILURE, errorMessage: error.status, }); } };Puede realizar un seguimiento de la cantidad de tiempo que ha pasado desde que comenzó el sondeo y salir cuando llega a cero.
const addDelay = timeout => new Promise(resolve => setTimeout(resolve, timeout)) export const myReport = () => async (dispatch) => { dispatch({ type: constants.DOWNLOAD_REPORT_REQUEST }) let url = `/admin/dashboard/report.js?project_id=${projectId}&tool_id=${toolId}` let remainingPollingTime = 15000 // <-------- try { const subscribe = async (uri) => { let response = await fetch(uri, { method: 'GET', headers: { 'content-type': 'application/json', 'x-api-token': `Bearer ${token}` } }) const resBody = await response.json() if (resBody.status === 'success') { window.location.href = resBody.url dispatch({ type: constants.DOWNLOAD_REPORT_SUCCESS }) } else { if(remainingPollingTime <= 0) { // <-------- dispatch({ type: constants.SHOW_DOWNLOAD_POPUP }) return } remainingPollingTime -= 5000 // <-------- await addDelay(5000) await subscribe(url) } } subscribe(url) } catch (error) { dispatch({ type: constants.DOWNLOAD_REPORT_FAILURE, errorMessage: error.status }) } }