Skip to content

Instantly share code, notes, and snippets.

@romgerman
Created July 6, 2019 14:55
Show Gist options
  • Save romgerman/dee59cf55c52a25d110d6c9285f896e1 to your computer and use it in GitHub Desktop.
Save romgerman/dee59cf55c52a25d110d6c9285f896e1 to your computer and use it in GitHub Desktop.
Sequencing async functions with callbacks
utils.sequence([
(ready) => connection.query(createPersonTableSQL, (error, results, fields) => {
ready()
}),
(ready) => connection.query(createPortfolioTableSQL, (error, results, fields) => {
ready()
}),
(ready) => connection.query(createDebtTableSQL, (error, results, fields) => {
ready()
}),
(ready) => connection.query(createCalendarTableSQL, (error, results, fields) => {
ready()
}),
(ready) => connection.query(createPaymentTableSQL, (error, results, fields) => {
ready()
})
], () => {
console.log("Migration finished")
completed()
})
/**
* Allows to call functions with callbacks in sequence
* @param {function[]} arr
* @param {function} completed
*/
function sequence(arr, completed) {
let index = -1
let ready = function() {
if (index !== arr.length - 1) {
callNext()
} else {
if (completed)
completed()
}
}
var callNext = function() {
index++
arr[index](ready)
}
callNext()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment