This is a test case from one company. I need to translate this function into Typescript and explain how to test it. But I even don't understand what is going on here. I understand every part of that code, but a whole picture still doesn't clear for me. Could someone explain how that piece of code works step by step?
I think I need some simple analog for this. Maybe some metaphor. Also, I'm not sure how to test that to see how this function should work.
// Makes your async function sequential. It means that next call won't be performed until the previous one finishes.
// This function is a wrapper for async functions
export function sequentialize(func: (...args: any[]) => any) {
// we create an immideately resolved promise
// we can use that because of closure mechanism
let previousCall: Promise<any> = Promise.resolve();
// return wrapper that will call original function with args
return function (...args: any[]): Promise<any> {
// Here I'm a bit confused. I know that with then we set a callback that
// will work after promise will be fullfiled. But why we save this in variable
const currentCall: Promise<any> = previousCall.then(() =>
// call original wrapped async function with args
func.apply(this, args)
);
console.log(currentCall);
// this part is not clear for me too
previousCall = currentCall.catch(() => {});
return currentCall;
};
}
// I use this code to test
const url = "https://jsonplaceholder.typicode.com/todos/1";
const myAsyncFunction = (url) => {
return fetch(url)
.then((response) => response.json())
.then((json) => console.log(json));
};
const sequentializeFunc = sequentialize(myAsyncFunction);
sequentializeFunc(url);
UPDATE: add ts and some comments to parts I already understand.