I’ve included questions + small hints (not full solutions unless you want them).
1. What will be the output of this code?
console.log("A"); Promise.resolve().then(() => console.log("B")); console.log("C"); Hint: Think microtask queue vs sync.
Expected order: A, C, B.
2. Rewrite this callback code using Promises
function getData(cb) { setTimeout(() => cb("done"), 1000); } Task: Convert to:
- a Promise
- async/await version
3. Create a function delay(ms) that returns a Promise
delay(1000).then(() => console.log("1 second passed")); Hint: Use setTimeout + resolve.
4. Implement promisify
Convert a callback-style function:
function add(a, b, callback) { callback(null, a + b); } into:
const addPromise = promisify(add); addPromise(2, 3).then(console.log); Hint: Resolve on success, reject on error.
5. What is the output?
Promise.resolve(1) .then((x) => x + 1) .then((x) => { throw new Error("Oops"); }) .catch(() => 10) .then((x) => console.log(x)); Hint: .catch() returns a value → chain continues.
6. Run promises in parallel and return results in order
const tasks = [ () => Promise.resolve(10), () => Promise.resolve(20), () => Promise.resolve(30) ]; runAll(tasks).then(console.log); // expected: [10, 20, 30] Hint: Use Promise.all.
7. Create a function that retries a Promise 3 times
retry(() => fetch("/api"), 3) .then(console.log) .catch(console.error); Hint: Loop + recursion + catch.
8. Output prediction
async function test() { console.log(1); await Promise.resolve(); console.log(2); } console.log(3); test(); console.log(4); Hint: await → microtask.
Expected: 3, 1, 4, 2.
9. Implement your own Promise.all()
Input:
myPromiseAll([p1, p2, p3]).then(...); Hint: Count resolved values + reject immediately.
10. Difference between these two — output?
Promise.resolve().then(() => console.log("A")); Promise.resolve().then(console.log("B")); Hint: Second one logs B immediately because you're calling the function.
11. Chain Promises without using .then()
Given:
async function f1() { return 10; } async function f2() { return 20; } Call them one after another and sum the result.
12. Why does this throw an error?
await Promise.resolve("hello"); Hint: Only allowed inside async functions.
13. Turn an array of URLs into fetched data (Promise + map)
const urls = ["a.com", "b.com", "c.com"]; fetchAll(urls).then(console.log); Hint: Map to fetch → Promise.all.
14. Explain and predict output
Promise.reject("err") .then(() => console.log("then")) .catch(() => console.log("catch")) .then(() => console.log("after catch")); 15. Create a timeout wrapper
timeout(fetch("/api"), 2000) .then(console.log) .catch(console.error); If Promise doesn’t resolve in 2 seconds → reject with timeout.
Top comments (0)