function delay(ms, val = true) {
let timeoutId;
return new Promise(resolve => {
timeoutId = setTimeout(() => resolve(val), ms);
});
}
function runTest(resultFunc) {
const res = resultFunc();
for(let i=0; i<20; i++) {
res.add(delay(i));
}
return res.get();
}
const createResultPromiseFunc = () => {
let res = Promise.resolve();
return {
get() { return res; },
add(nextPromise) {
res = res.then(() => nextPromise);
return this;
}
};
};
runTest(createResultPromiseFunc);
const createResultPromiseArray = () => {
const res = [];
return {
get() { return Promise.all(res); },
add(nextPromise) {
res.push(nextPromise);
return this;
}
};
};
runTest(createResultPromiseArray);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Function based | |
Array based |
Test name | Executions per second |
---|---|
Function based | 4942.2 Ops/sec |
Array based | 5790.7 Ops/sec |
I'll break down the provided benchmarking data and explain what's being tested, compared, and some pros and cons of each approach.
Benchmark Definition JSON
The benchmark definition represents two different ways to implement a "Multipromise Resulter" in JavaScript:
createResultPromiseFunc
that returns an object with two methods: get()
and add(nextPromise)
. The get()
method returns the resolved promise, while the add(nextPromise)
method adds the next promise to the chain.createResultPromiseArray
that returns an object with two methods: get()
and add(nextPromise)
. However, instead of using a promise, it returns an array that is populated with promises through the add()
method. The get()
method then resolves to the all-promise resolved in the array.Options Compared
The benchmark compares the performance of these two different approaches:
add()
method.Pros and Cons of Each Approach
Function-Based Implementation:
Pros:
Cons:
Array-Based Implementation:
Pros:
push()
.Cons:
Library Used (if applicable)
In both benchmark definitions, no external libraries are used. The implementations rely solely on JavaScript's built-in features, such as Promise
objects and array methods.
Special JS Features or Syntax
No special JavaScript features or syntax are used in these benchmark definitions. They rely only on standard JavaScript constructs.
Other Alternatives
Other alternatives to implement a "Multipromise Resulter" could include:
async/await
with Promise.all()
or Promise.race()
Keep in mind that each of these alternatives would have their own pros and cons, and the choice ultimately depends on the specific requirements and constraints of the project.