LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 20 of 25

Promises Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Promises · Study material

A Promise is an object representing a value that will be available later – the result of a network request, a file read or a timer. It starts pending and settles exactly once, either fulfilled with a value or rejected with a reason. Promises fixed the problems of callbacks – nesting, scattered error handling and untrustworthy callers – and they are the foundation of fetch, async/await and almost every modern API. Interviews test exactly how they behave: when the executor runs, what then returns, how errors propagate, why then callbacks run before timers, and the differences between all, allSettled, race and any. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

States

A promise is pending until its producer calls resolve(value) or reject(reason). After that it is settled – fulfilled or rejected – and never changes again. Code that consumes it registers callbacks with then, catch and finally.

// A promise is pending, then settles once: fulfilled (with a value) or rejected (with a reason)
const PENDING = Symbol("pending");
const stateOf = (p) =>
  Promise.race([p, PENDING]).then(
    (v) => (v === PENDING ? "pending" : `fulfilled (${v})`),
    (e) => `rejected (${e.message})`,
  );

const ok = new Promise((resolve) => resolve("data"));
const failed = new Promise((_, reject) => reject(new Error("network down")));
const waiting = new Promise(() => {});          // never settles
Promise.all([stateOf(ok), stateOf(failed), stateOf(waiting)]).then((s) => console.log(s.join(" | ")));

Output

fulfilled (data) | rejected (network down) | pending

The executor runs synchronously; promises settle once

new Promise((resolve, reject) => { … }) runs the executor function immediately, during the constructor call. Only the first call to resolve or reject counts; later calls are ignored. Callbacks passed to then never run synchronously – even for an already-settled promise they are queued as microtasks.

console.log("1. before");
const p = new Promise((resolve, reject) => {
  console.log("2. the executor runs immediately");
  resolve("first");
  resolve("second");            // ignored: a promise settles only once
  reject(new Error("too late")); // ignored too
});
p.then((v) => console.log("4. then:", v));   // then callbacks always run later (as microtasks)
console.log("3. after");

Output

1. before
2. the executor runs immediately
3. after
4. then: first

Chaining

then always returns a new promise, resolved with whatever the callback returns. Return a plain value and it is passed to the next then; return a promise and the chain waits for it (promises are flattened); return nothing and the next step receives undefined – the most common promise bug is a forgotten return.

Promise.resolve(2)
  .then((n) => n * 10)                                                   // return a value → passed on
  .then((n) => new Promise((r) => setTimeout(() => r(n + 5), 10)))       // return a promise → the chain waits
  .then((n) => { console.log("result:", n); })                           // returns nothing (undefined)
  .then((v) => console.log("next gets:", v));

Output

result: 25
next gets: undefined

Error handling

A thrown error or a rejected promise anywhere in the chain skips the following then callbacks until a catch (or a then with a second, rejection callback). catch handles it and returns a new promise – fulfilled with whatever catch returns, so the chain can recover. finally runs on both outcomes, receives no value and passes the original result through (unless it throws).

Promise.resolve("start")
  .then(() => { throw new Error("step 2 failed"); })
  .then(() => console.log("skipped"))                       // skipped: the chain is now rejected
  .catch((e) => {
    console.log("caught:", e.message);
    return "recovered";                                     // a value from catch fulfils the chain again
  })
  .then((v) => console.log("continues with:", v))
  .finally(() => console.log("finally: always runs"));

Output

caught: step 2 failed
continues with: recovered
finally: always runs

Microtasks run before timers

Promise callbacks go into the microtask queue, which is emptied completely after the current synchronous code and before the next timer or I/O callback (a task). So a then callback always runs before a setTimeout(…, 0) callback scheduled at the same time. The Event Loop topic covers the full order.

setTimeout(() => console.log("3. timeout (task)"), 0);
Promise.resolve().then(() => console.log("2. then (microtask)"));
console.log("1. sync");
// All synchronous code first, then every microtask, then the next timer

Output

1. sync
2. then (microtask)
3. timeout (task)

Combining promises

MethodFulfils whenRejects when
Promise.allall fulfil (values in input order)any rejects – immediately (fail-fast)
Promise.allSettledall settle – with { status, value | reason } objectsnever
Promise.racethe first to settle fulfilsthe first to settle rejects
Promise.anythe first to fulfilall reject – with an AggregateError
const delay = (ms, v, fail = false) =>
  new Promise((res, rej) => setTimeout(() => (fail ? rej(new Error(v)) : res(v)), ms));

Promise.all([delay(20, "a"), delay(10, "b")]).then((v) => console.log("all:", v));            // all must succeed
Promise.allSettled([delay(5, "ok"), delay(5, "bad", true)])
  .then((r) => console.log("allSettled:", r.map((x) => x.status)));                            // never rejects
Promise.race([delay(15, "slow"), delay(5, "fast")]).then((v) => console.log("race:", v));     // first to settle
Promise.any([delay(5, "e1", true), delay(12, "winner")]).then((v) => console.log("any:", v)); // first to succeed

Output

allSettled: [ 'fulfilled', 'rejected' ]
race: fast
any: winner
all: [ 'a', 'b' ]

Promise.resolve, Promise.reject and thenables

Promise.resolve(x) returns x itself if it is already a promise, adopts any thenable (an object with a then method) and otherwise wraps the value. Promise.reject(reason) creates a rejected promise. A rejection that is never handled triggers an unhandled rejection – in Node.js that terminates the process.

const p = Promise.resolve(1);
console.log(Promise.resolve(p) === p);       // a real promise is returned as it is
// Any object with a then method ("thenable") is adopted by promises
const thenable = { then(resolve) { resolve(42); } };
Promise.resolve(thenable).then((v) => console.log("thenable gave", v));
Promise.reject(new Error("nope")).catch((e) => console.log("rejected with", e.message));
// (adopting a thenable takes one extra microtask, so the rejection above is reported first)

Output

true
rejected with nope
thenable gave 42

Common mistakes

  • Forgetting return inside then – the next step gets undefined and does not wait.
  • Nesting then calls instead of returning the inner promise – timing and errors break.
  • No catch at the end of a chain – unhandled rejections (Node.js exits).
  • Expecting forEach to wait for promises – use Promise.all with map.
  • Using Promise.all when some calls may fail – use allSettled.
  • Wrapping existing promises in new Promise – errors are easily lost; return the chain.
  • Thinking then runs synchronously – callbacks always run later, as microtasks.

Key points to remember

  • Pending → fulfilled or rejected, exactly once.
  • The executor runs synchronously; then/catch/finally callbacks run asynchronously.
  • then returns a new promise; returned promises are flattened.
  • Errors skip to the next catch; catch can recover the chain.
  • finally runs on both outcomes and passes the result through.
  • Microtasks (promise callbacks) run before the next timer.
  • all (fail-fast), allSettled (never rejects), race (first settled), any (first fulfilled).

Frequently asked questions

Promises or async/await?

async/await is syntax built on promises: an async function returns a promise and await waits for one. Use whichever reads best – most code uses await, while combinators like Promise.all are still promise methods.

Can a promise be cancelled?

Not directly. APIs such as fetch use an AbortController to stop the underlying work, which then rejects the promise.

Why does Node.js crash on an unhandled rejection?

Since Node.js 15 an unhandled rejection is treated like an uncaught exception, because silently ignoring failures hides bugs. Always end chains with catch (or try…catch around await).

Where can I learn more?

Read Promises, async and await and The Event Loop in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links