问题
I have a function which accepts a string and a path value and checks whether the path at the result returns a 1 or a -1. I fire the function with multiple requests and everything seems to be successful except for one. For example, if I call the function with 10 different URL's continously (one by one, not in an array), the promise is resolved for 9 but not for the 10th one.
This is my code:
enum Status {
Queued = 0,
Started = 1,
Finished = 2,
Failed = -1,
}
let dataFetchingTimer: number;
export const getDataAtIntervals = (url: string, path: string): Promise<any> => {
clearTimeout(dataFetchingTimer);
return new Promise<any>((resolve: Function, reject: Function): void => {
try {
(async function loop() {
const result = await API.load(url);
console.log(`${url} - ${JSON.stringify(result)}`)
if (
get(result, path) &&
(get(result, path) === Status.Finished ||
get(result, path) === Status.Failed)
) {
return resolve(result); // Resolve with the data
}
dataFetchingTimer = window.setTimeout(loop, 2500);
})();
} catch (e) {
reject(e);
}
});
};
export const clearGetDataAtIntervals = () => clearTimeout(dataFetchingTimer);
Please advice. In the above image, 4535 is called only once. and is not called until 2 or -1 is returned.
回答1:
Using a single timeout for all your calls might be the cause of weird behaviors. A solution to avoid collisions between your calls might be to use a timeout per call. You could do something along these lines (I used simple JS because I'm not used to Typescript):
const Status = {
Queued: 0,
Started: 1,
Finished: 2,
Failed: -1,
}
let dataFetchingTimerMap = {
// Will contain data like this:
// "uploads/4541_status": 36,
};
const setDataFetchingTimer = (key, cb, delay) => {
// Save the timeout with a key
dataFetchingTimerMap[key] = window.setTimeout(() => {
clearDataFetchingTimer(key); // Delete key when it executes
cb(); // Execute the callback
}, delay);
}
const clearDataFetchingTimer = (key) => {
// Clear the timeout
clearTimeout(dataFetchingTimerMap[key]);
// Delete the key
delete dataFetchingTimerMap[key];
}
const getDataAtIntervals = (url, path) => {
// Create a key for the timeout
const timerKey = `${url}_${path}`;
// Clear it making sure you're only clearing this one (by key)
clearDataFetchingTimer(timerKey);
return new Promise((resolve, reject) => {
// A try/catch is useless here (https://jsfiddle.net/4wpezauc/)
(async function loop() {
// It should be here (https://jsfiddle.net/4wpezauc/2/)
try {
const result = await API.load(url);
console.log(`${url} - ${JSON.stringify(result)}`);
if ([Status.Finished, Status.Failed].includes(get(result, path))) {
return resolve(result); // Resolve with the data
}
// Create your timeout and save it with its key
setDataFetchingTimer(timerKey, loop, 2500);
} catch (e) {
reject(e);
}
})();
});
};
const clearGetDataAtIntervals = () => {
// Clear every timeout
Object.keys(dataFetchingTimerMap).forEach(clearDataFetchingTimer);
};
来源:https://stackoverflow.com/questions/65694196/poll-api-until-a-path-in-the-response-object-is-successful-failure-typescrip