I'm reviewing a React test, and I have a problem with asynchronous programming.
The requirements are:
It takes 7 minutes to get returned response after requesting data. But, when the response is delayed for 30 seconds, a timeout error will occur.
Check the API specs, fulfill these requirements:
And the API is:
import { rest } from 'msw';
export function handlers() {
return [
rest.get('/api/data', getData),
rest.get('/api/data/progress', getDataProgress),
];
};
const getData = async (req, res, ctx) => {
let wait = req.url.searchParams.get('wait');
if (wait !== 'no') {
wait = 'yes';
}
try {
startNewGetData();
if (wait === 'yes') {
await Promise.race([waitLastGetData, timeout(minutes(7)), timeoutError(minutes(0.5))]);
}
return res(ctx.status(200));
} catch {
return res(ctx.status(500));
}
};
const getDataProgress = (_, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
hasFinished: hasGetDataFinished,
})
);
};
let waitLastGetData = undefined;
let hasGetDataFinished = false;
function startNewGetData() {
hasGetDataFinished = false;
waitLastGetData = new Promise(resolve => setTimeout(resolve, minutes(3)));
waitLastGetData.then(() => (hasGetDataFinished = true));
}
I don't even know what I should first touch. Could you please tell me what I should do to fulfill those requirements?
You might not understand my English well because of my short English, sorry for that.