All Projects → toniov → P Iteration

toniov / P Iteration

Utilities that make array iteration easy when using async/await or Promises

Programming Languages

javascript
184084 projects - #8 most used programming language
es2017
19 projects

Projects that are alternatives of or similar to P Iteration

P Map
Map over promises concurrently
Stars: ✭ 639 (+89.61%)
Mutual labels:  async, promise, async-await, await
Await Of
await wrapper for easier errors handling without try-catch
Stars: ✭ 240 (-28.78%)
Mutual labels:  async, promise, async-await, await
Breeze
Javascript async flow control manager
Stars: ✭ 38 (-88.72%)
Mutual labels:  async, promise, await
Emacs Async Await
Async/Await for Emacs
Stars: ✭ 47 (-86.05%)
Mutual labels:  async, promise, await
Promise Fun
Promise packages, patterns, chat, and tutorials
Stars: ✭ 3,779 (+1021.36%)
Mutual labels:  async, promise, async-await
Wx Promise Pro
✨强大、优雅的微信小程序异步库🚀
Stars: ✭ 762 (+126.11%)
Mutual labels:  async, promise, await
Ws Promise Client
PROJECT MOVED: https://github.com/kdex/ws-promise
Stars: ✭ 6 (-98.22%)
Mutual labels:  async, promise, await
Unityfx.async
Asynchronous operations (promises) for Unity3d.
Stars: ✭ 143 (-57.57%)
Mutual labels:  async, promise, async-await
Use Async Effect
🏃 Asynchronous side effects, without the nonsense
Stars: ✭ 193 (-42.73%)
Mutual labels:  async, async-await, await
Asyncex
A helper library for async/await.
Stars: ✭ 2,794 (+729.08%)
Mutual labels:  async, async-await, await
Coerce Rs
Coerce - an asynchronous (async/await) Actor runtime and cluster framework for Rust
Stars: ✭ 231 (-31.45%)
Mutual labels:  async, async-await, await
arraync
Async Array methods polyfills
Stars: ✭ 16 (-95.25%)
Mutual labels:  promise, array, async-await
Awaitkit
The ES8 Async/Await control flow for Swift
Stars: ✭ 709 (+110.39%)
Mutual labels:  async, promise, await
Then
🎬 Tame async code with battle-tested promises
Stars: ✭ 908 (+169.44%)
Mutual labels:  async, promise, async-await
Swiftcoroutine
Swift coroutines for iOS, macOS and Linux.
Stars: ✭ 690 (+104.75%)
Mutual labels:  async, async-await, await
Rubico
[a]synchronous functional programming
Stars: ✭ 133 (-60.53%)
Mutual labels:  async, promise, async-await
Await Handler
Basic wrapper for await that allows handling of errors without try/catch blocks
Stars: ✭ 13 (-96.14%)
Mutual labels:  promise, async-await, await
Posterus
Composable async primitives with cancelation, control over scheduling, and coroutines. Superior replacement for JS Promises.
Stars: ✭ 536 (+59.05%)
Mutual labels:  async, promise, async-await
Kitsu
🦊 A simple, lightweight & framework agnostic JSON:API client
Stars: ✭ 166 (-50.74%)
Mutual labels:  async, promise, async-await
Metasync
Asynchronous Programming Library for JavaScript & Node.js
Stars: ✭ 164 (-51.34%)
Mutual labels:  array, async, promise

p-iteration Build Status NPM version

Make array iteration easy when using async/await and promises

  • Same functionality as the ES5 Array iteration methods we all know
  • All the methods return a Promise, making them awaitable and thenable
  • Allow the usage of async functions as callback
  • Callbacks run concurrently
  • Lightweight (no prd dependencies)

Install

$ npm install --save p-iteration

Usage

Smooth asynchronous iteration using async/await:

const { map } = require('p-iteration');

// map passing an async function as callback
function getUsers (userIds) {
  return map(userIds, async userId => {
    const response = await fetch(`/api/users/${userId}`);
    return response.json();
  });
}

// map passing a non-async function as callback
async function getRawResponses (userIds) {
  const responses = await map(userIds, userId => fetch(`/api/users/${userId}`));
  // ... do some stuff
  return responses;
}

// ...
const { filter } = require('p-iteration');

async function getFilteredUsers (userIds, name) {
  const filteredUsers = await filter(userIds, async userId => {
    const response = await fetch(`/api/users/${userId}`);
    const user = await response.json();
    return user.name === name;
  });
  // ... do some stuff
  return filteredUsers;
}

// ...

All methods return a Promise so they can just be used outside an async function just with plain Promises:

const { map } = require('p-iteration');

map([123, 125, 156], (userId) => fetch(`/api/users/${userId}`))
  .then((result) => {
    // ...
  })
  .catch((error) => {
    // ...
  });

If there is a Promise in the array, it will be unwrapped before calling the callback:

const { forEach } = require('p-iteration');
const fetchJSON = require('nonexistent-module');

function logUsers () {
  const users = [
    fetchJSON('/api/users/125'), // returns a Promise
    { userId: 123, name: 'Jolyne', age: 19 },
    { userId: 156, name: 'Caesar', age: 20 }
  ];
  return forEach(users, (user) => {
    console.log(user);
  });
}
const { find } = require('p-iteration');
const fetchJSON = require('nonexistent-module');

function findUser (name) {
  const users = [
    fetchJSON('/api/users/125'), // returns a Promise
    { userId: 123, name: 'Jolyne', age: 19 },
    { userId: 156, name: 'Caesar', age: 20 }
  ];
  return find(users, (user) => user.name === name);
}

The callback will be invoked as soon as the Promise is unwrapped:

const { forEach } = require('p-iteration');

// function that returns a Promise resolved after 'ms' passed
const delay = (ms) => new Promise(resolve => setTimeout(() => resolve(ms), ms));

// 100, 200, 300 and 500 will be logged in this order
async function logNumbers () {
  const numbers = [
    delay(500),
    delay(200),
    delay(300),
    100
  ];
  await forEach(numbers, (number) => {
    console.log(number);
  });
}

API

The methods are implementations of the ES5 Array iteration methods we all know with the same syntax, but all return a Promise. Also, with the exception of reduce(), all methods callbacks are run concurrently. There is a series version of each method, called: ${methodName}Series, series methods use the same API that their respective concurrent ones.

There is a link to the original reference of each method in the docs of this module:

Instance methods

Extending native objects is discouraged and I don't recommend it, but in case you know what you are doing, you can extend Array.prototype to use the above methods as instance methods. They have been renamed as async${MethodName}, so the original ones are not overwritten.

const { instanceMethods } = require('p-iteration');

Object.assign(Array.prototype, instanceMethods);

async function example () {
  const foo = await [1, 2, 3].asyncMap((id) => fetch(`/api/example/${id}`));
}

License

MIT © Antonio V

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].