What is p-map-series?
The p-map-series npm package allows you to map over promises serially. It processes each promise one after another, ensuring that only one promise is running at a time. This is useful for tasks that need to be performed in sequence rather than in parallel.
What are p-map-series's main functionalities?
Serial Processing
This feature allows you to process an array of promise-returning functions in series. Each task is executed one after another, ensuring that only one task is running at any given time.
const pMapSeries = require('p-map-series');
const tasks = [
() => Promise.resolve('Task 1'),
() => Promise.resolve('Task 2'),
() => Promise.resolve('Task 3')
];
pMapSeries(tasks).then(results => {
console.log(results); // ['Task 1', 'Task 2', 'Task 3']
});
Error Handling
This feature demonstrates how p-map-series handles errors. If any task in the series fails, the entire process stops, and the error is caught in the catch block.
const pMapSeries = require('p-map-series');
const tasks = [
() => Promise.resolve('Task 1'),
() => Promise.reject(new Error('Task 2 failed')),
() => Promise.resolve('Task 3')
];
pMapSeries(tasks).then(results => {
console.log(results);
}).catch(error => {
console.error(error); // Error: Task 2 failed
});
Other packages similar to p-map-series
p-series
The p-series package allows you to run promise-returning & async functions in series. It is similar to p-map-series but focuses solely on running promises in sequence without the mapping functionality.
promise-sequential
The promise-sequential package runs an array of promise-returning functions sequentially. It is similar to p-map-series but is designed to be lightweight and straightforward, focusing solely on sequential execution.
p-map-series
Map over promises serially
Useful as a side-effect mapper. Use p-map
if you don't need side-effects, as it's concurrent.
Install
$ npm install p-map-series
Usage
import pMapSeries from 'p-map-series';
const keywords = [
getTopKeyword()
'rainbow',
'pony'
];
let scores = [];
const mapper = async keyword => {
const score = await fetchScore(keyword);
scores.push(score);
return {keyword, score};
});
console.log(await pMapSeries(keywords, mapper));
API
pMapSeries(input, mapper)
Returns a Promise
that is fulfilled when all promises in input
and ones returned from mapper
are fulfilled, or rejects if any of the promises reject. The fulfilled value is an Array
of the mapper
created promises fulfillment values.
input
Type: Iterable<Promise | unknown>
Mapped over serially in the mapper
function.
mapper(element, index)
Type: Function
Expected to return a value. If it's a Promise
, it's awaited before continuing with the next iteration.
Related
- p-each-series - Iterate over promises serially
- p-reduce - Reduce a list of values using promises into a promise for a value
- p-map - Map over promises concurrently
- More…