Delay with PromiseProblem StatementWrite a function `delay(ms)` that returns a Promise that resolves after `ms` milliseconds.Approach 1. Create a new Promise. 2. Inside, use `setTimeout`. 3. Call `resolve` when the timeout completes. Solution`function delay(ms) { return new Promise(resolve => { setTimeout(resolve, ms);
Basic Async/AwaitProblem StatementWrite an async function `getAsyncMessage()` that waits for 100ms using the `delay` function and then returns "Done!".Approach 1. Mark function as `async`. 2. Use `await` with the delay. Solution`async function getAsyncMessage() { await delay(100); return "Done!";
Parallel ExecutionProblem StatementWrite a function `waitAll(promises)` that takes an array of promises and returns a promise that resolves when all of them are finished.Approach 1. Use `Promise.all(promises)`. Solution`function waitAll(promises) { return Promise.all(promises);
Fastest PromiseProblem StatementWrite a function `raceFirst(promises)` that returns the result of the first promise that settles.Approach 1. Use `Promise.race(promises)`. Solution`function raceFirst(promises) { return Promise.race(promises);
Instant ResolveProblem StatementWrite a function `wrapValue(val)` that returns a Promise already resolved with that value.Approach 1. Use `Promise.resolve(val)`. Solution`function wrapValue(val) { return Promise.resolve(val);
Instant RejectionProblem StatementWrite a function `failFast()` that returns a Promise that is already rejected with the message "Error".Approach 1. Use `Promise.reject("Error")`. Solution`function failFast() { return Promise.reject("Error");
Async Error HandlingProblem StatementWrite an async function `safeFetch(fn)` that calls `fn` (which returns a promise). If it fails, return "Caught Error".Approach 1. Use a `try...catch` block inside the async function. Solution`async function safeFetch(fn) { try { return await fn();
Fetch JSONProblem StatementWrite an async function `fetchData(url)` that fetches data from a URL and returns the parsed JSON.Approach 1. Use `fetch(url)`. 2. Await the response, then call `.json()` and await that too. Solution`async function fetchData(url) { const response = await fetch(url); return await response.json();
Simple Promise ChainProblem StatementWrite a function `chain(promise, nextFn)` that waits for the promise and then calls `nextFn` with the result.Approach 1. Use `.then(nextFn)`. Solution`function chain(promise, nextFn) { return promise.then(nextFn);
Sequential Async LoopProblem StatementWrite a function `processInOrder(items, asyncFn)` that executes `asyncFn(item)` one by one, waiting for each to finish.Approach 1. Use a `for...of` loop inside an async function. 2. `await` the call inside the loop. Solution`async function processInOrder(items, asyncFn) { for (let item of items) { await asyncFn(item);
Promise with TimeoutProblem StatementWrite a function `withTimeout(promise, ms)` that rejects if the promise doesn't resolve within `ms` milliseconds.Approach 1. Use `Promise.race()`. 2. Create a "timeout promise" that rejects after `ms`. Solution`function withTimeout(promise, ms) { const timeout = new Promise((_, reject) => setTimeout(() => reject("Timed out"), ms) ); return Promise.race([promise, timeout]);
Parallel Async MapProblem StatementWrite a function `mapAsync(arr, fn)` that starts all calls to `fn(item)` in parallel and returns their results in an array.Approach 1. Use `arr.map(fn)` to get an array of promises. 2. Return `Promise.all()` on that array. Solution`function mapAsync(arr, fn) { return Promise.all(arr.map(fn));
Wait for All (Settled)Problem StatementWrite a function `checkAll(promises)` that waits for all promises to settle (either resolve or reject) using `Promise.allSettled()`.Approach 1. Use `Promise.allSettled(promises)`. Solution`function checkAll(promises) { return Promise.allSettled(promises);
Simple Retry LogicProblem StatementWrite an async function `retry(fn, retries)`. If `fn()` fails, try again up to `retries` times.Approach 1. Use a loop up to `retries`. 2. Use `try...catch`. On fail, if retries left, continue. Else, throw. Solution`async function retry(fn, retries) { for (let i = 0; i < retries; i++) { try { return await fn();
Promisify CallbackProblem StatementWrite a function `promisify(fn)` that takes a function that accepts a callback (err, data) and converts it to return a Promise.Approach 1. Return a function that returns a new Promise. 2. Invoke the original function with arguments and a custom callback. Solution`function promisify(fn) { return function(...args) { return new Promise((resolve, reject) => { fn(...args, (err, data) => { if (err) reject(err); else resolve(data);
Simple Async GeneratorProblem StatementWrite an async generator `rangeGen(start, end)` that yields values from start to end with a 50ms delay between each.Approach 1. Use `async function*`. 2. `await delay(50)` before each `yield`. Solution`async function* rangeGen(start, end) { for (let i = start; i <= end; i++) { await new Promise(r => setTimeout(r, 50)); yield i;
Finally BlockProblem StatementWrite a function `alwaysRun(promise, cleanup)` that calls `cleanup()` regardless of whether the promise resolves or rejects.Approach 1. Use `.finally(cleanup)`. Solution`function alwaysRun(promise, cleanup) { return promise.finally(cleanup);
Sleep FunctionProblem StatementWrite an async function `sleepAndReturn(val, ms)` that returns `val` after sleeping for `ms`.Approach 1. Create a promise that resolves after a timeout and await it. Solution`async function sleepAndReturn(val, ms) { await new Promise(resolve => setTimeout(resolve, ms)); return val;
Promise AnyProblem StatementWrite a function `getFirstSuccess(promises)` that returns the first successful promise result using `Promise.any()`.Approach 1. `Promise.any()` ignores rejections unless all reject. Solution`function getFirstSuccess(promises) { return Promise.any(promises);
Abort ControllerProblem StatementWrite a function `fetchWithSignal(url, signal)` that returns a fetch call, allowing it to be cancelled by passing the `{ signal }` in fetch options.Approach 1. Pass `{ signal }` in the fetch options. Solution`function fetchWithSignal(url, signal) { return fetch(url, { signal