Created
January 20, 2017 17:20
-
-
Save jerryharrison/86f6f421279f8a96e22165af7c7cd765 to your computer and use it in GitHub Desktop.
Promises in sequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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