ember-async-await-for-each

0.1.1 • Public • Published

ember-async-await-for-each

Ship Shape

ember-async-await-for-each is built and maintained by Ship Shape. Contact us for Ember.js consulting, development, and training for your project.

npm version Download count all time npm Ember Observer Score Build Status Code Climate Test Coverage

async/await aware forEach for Ember. Concept taken from this great article on async/await in forEach.

Compatibility

  • Ember.js v3.4 or above
  • Ember CLI v2.13 or above
  • Node.js v8 or above

Installation

ember install ember-async-await-for-each

Usage

First you will want to import asyncForEach

import asyncForEach from 'ember-async-await-for-each';

You can then use it inside of any async functions and await its result. An example of how you could use it to save addresses for a person model is below.

const saveAddresses = async () => {
  await asyncForEach(person.get('addresses').toArray(), async (address) => {
    const address = await person.get('address');
 
    if (address.get('isDirty')) {
      return await address.save();
    }
  });
};
 
saveAddresses();

You can continue to wrap this in other async functions as well.

const doOtherAsyncStuff = async () => {
  await saveAddresses();
  await otherFunction();
  // etc
};

Serial vs parallel execution

asyncForEach resolves the callbacks in a serial fashion. This means that it waits until a callback is fully resolved before moving onto the next element in the list.

To launch all callbacks in parallel, you would have to do something like below instead:

import { all } from 'rsvp';
 
const saveAddressesParallel = async () => {
  await all(person.get('addresses').toArray().map(async (address) => {
    const address = await person.get('address');
 
    if (address.get('isDirty')) {
      return await address.save();
    }
  }));
};

Contributing

See the Contributing guide for details.

License

This project is licensed under the MIT License.

Package Sidebar

Install

npm i ember-async-await-for-each

Weekly Downloads

1

Version

0.1.1

License

MIT

Unpacked Size

6.6 kB

Total Files

6

Last publish

Collaborators

  • rwwagner90