Overview
Implement promiseMerge(fn) that wraps an async function so concurrent calls with the same key share a single in-flight promise.
Examples
const fetch = promiseMerge(async (id) => api.get(id));
// Two concurrent calls for same id share one request
const [a, b] = await Promise.all([fetch('1'), fetch('1')]); // only 1 call madeSolution
Reveal solution
function promiseMerge(fn) {
const pending = new Map();
return function(key) {
if (pending.has(key)) return pending.get(key);
const promise = fn(key).finally(() => pending.delete(key));
pending.set(key, promise);
return promise;
};
}promise-merge.js
Promise Merge
mediumcodingJavaScriptPromises
Overview
Implement promiseMerge(fn) that wraps an async function so concurrent calls with the same key share a single in-flight promise.
Examples
const fetch = promiseMerge(async (id) => api.get(id));
// Two concurrent calls for same id share one request
const [a, b] = await Promise.all([fetch('1'), fetch('1')]); // only 1 call madeSolution
Reveal solution
function promiseMerge(fn) {
const pending = new Map();
return function(key) {
if (pending.has(key)) return pending.get(key);
const promise = fn(key).finally(() => pending.delete(key));
pending.set(key, promise);
return promise;
};
}NameTopicDifficulty
103 of 103 problems