Skip to content

Instantly share code, notes, and snippets.

@jerryharrison
Created January 20, 2017 17:20
Show Gist options
  • Save jerryharrison/86f6f421279f8a96e22165af7c7cd765 to your computer and use it in GitHub Desktop.
Save jerryharrison/86f6f421279f8a96e22165af7c7cd765 to your computer and use it in GitHub Desktop.
Promises in sequence.
// Syncronus running of promises to process an array of objs (or anything really) in a series.
// given an array:
var items = [{type: 'peanuts', type: 'carrots'}];
// we instantly "resolve" a promise for force exceucution
let sequence = Promise.resolve();
for (let item of items) {
sequence = sequence.then(() => {
return new Promise((resolve, reject) => {
db.insertOrUpdateThing(item, {err, dbItem} => {
// yay we have a new item in our db
if (err) {
return reject(err);
}
return resolve(dbItem);
});
})
});
}
return sequence;
// or
sequence
.then(items => {
// array of values returned from resolve fxns
// do things
})
.catch(err => {
console.log(err);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment