0.1.1 • Published 5 years ago
ember-async-await-for-each v0.1.1
ember-async-await-for-each
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.