Code Logo

Chain Promises with then()

Published at25 Jul 2026
JavaScript Functions Hard 0 views
Like0

Write a JavaScript function that takes a number and returns a Promise that resolves with the value doubled, then checks if the doubled value is divisible by 3. The function uses Promise.resolve().then() to chain transformations asynchronously.

Promises are JavaScript's primary mechanism for handling asynchronous operations. A Promise represents a value that may be available now, later, or never. The .then() method attaches callbacks that execute when the Promise settles. Each .then() returns a new Promise, enabling method chaining for sequential async operations.

The Promise chain pattern is fundamental to modern JavaScript. Promises avoid the "callback hell" of nested callbacks by providing a flat chain structure. Error handling is centralized in a single .catch() at the end of the chain. Since ES2017, async/await provides syntactic sugar over Promises, but understanding raw .then() chains is essential for deep JavaScript knowledge.

Time complexity is O(1) for the synchronous transformations. The asynchronous nature means the .then() callbacks execute on the microtask queue after the current synchronous code completes. The Promise.resolve() method creates an immediately resolved Promise.

Edge cases include zero (0*2=0, 0%3=0 -> true), negative numbers, and ensuring the chain correctly passes the transformed value from each step to the next .then().

Example Input & Output

Example 1
Input
4
Output
false
Explanation

4*2=8, 8%3=2 -> false

Example 2
Input
3
Output
true
Explanation

3*2=6, 6%3=0 -> true

Example 3
Input
0
Output
true
Explanation

0*2=0, 0%3=0 -> true

Example 4
Input
6
Output
true
Explanation

6*2=12, 12%3=0 -> true

Example 5
Input
1
Output
false
Explanation

1*2=2, 2%3=2 -> false

Algorithm Flow

Recommendation Algorithm Flow for Chain Promises with then()
Recommendation Algorithm Flow for Chain Promises with then()

Solution Approach

function solution(n) {
  return Promise.resolve(n)
    .then(function(x) { return x * 2; })
    .then(function(x) { return x % 3 === 0; });
}

Best Answers

javascript - Approach 1
function solution(n) {
  return Promise.resolve(n)
    .then(function(x) { return x * 2; })
    .then(function(x) { return x % 3 === 0; });
}