← JavaScript Coding

Promise Merge

medium
Asked at
Meta
Meta

Problem statement

Implement a function that accepts two promises and returns a single Promise. This returned promise fulfills when both input promises fulfill, with a single value according to the following merge rules:

  • Numbers: Should be added together.
  • Strings: Should be concatenated.
  • Arrays: Should be combined into a single array (flat).
  • Plain Objects: Should be merged into a single object (shallow merge).

Rejection Cases

The returned promise should be rejected if:

  • The types of the fulfilled results do not match (e.g., a number and an array). Reject with the string 'Unsupported data types'.
  • One of the input promises fails. Reject with the reason from the failing promise.

Example

await promiseMerge(Promise.resolve(1), Promise.resolve(2)); // 3
await promiseMerge(Promise.resolve('abc'), Promise.resolve('def')); // 'abcdef'
await promiseMerge(Promise.resolve({ a: 1 }), Promise.resolve({ b: 2 })); // { a: 1, b: 2 }

How to approach Promise Merge

The strategy an interviewer expects you to reach for.

Promise merge waits on two promises, then combines values by type — add numbers, concat strings, reject on mismatched types. Naive move Chain p1.then(() => p2) serially, or coerce everything with + and hope. Where it breaks You need both results. Type mismatch should reject. If either input rejects, the merge should reject (fail-fast via Promise.all). The fix Promise.all([p1,p2]).then(([a,b]) => …) with explicit typeof branches for number/number and string/string; otherwise reject. Remember: all for coordination; typeof for the merge rule — no silent coercion. Say this in the interview: I'd Promise.all both inputs, then add numbers or concat strings, and reject when the resolved types do not match the allowed pairs.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingEasy

City Fetcher API

JS CodingHard

promise.all( )

JS CodingHard

promise.allSettled( )

JS CodingHard

promise.any( )

JS CodingHard

promise.race( )

JS CodingEasy

promise.reject()

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Meta interview