In this code:
new Promise((resolve, reject) => {
DB.get(params, function(err, data) {
if (err) reject(err)
else resolve(data.Item)
})
})
.then((data) => {
let params = { Name: 'DEMO' }
CWevents.putRule(params, function(err, data) {
if (err) console.log("Error", err)
else console.log("Success")
})
})
.then(() => {
let params = { Rule: 'DEMO' }
CWevents.putTargets(params, function(err, data) {
if (err) console.log("Error", err)
else console.log("Success", data)
})
})
The DB.get function here has a callback, but it would look awful to put multiple callbacks into each other, so I decided to use promises. I create a new promise, inside which is an asynchronous function. After it finishes running, it resolves and the first .then starts working, as desired. Then inside that first .then I have another asynchronous function that works much like the first one.
But there's no resolve/reject to run this time. So the third .then runs before the function inside second .then is finished. How can I make the third .then wait until the second one finished running? So function 1 finishes running, then function 2, then 3?
resolve()andreject()instead of theconsole.log()s?.then()handler and they will sequence properly and errors will work properly. Step 1, promisify all your asynchronous operations.util.promisify()is your friend here. Or, most databases these days have a built-in promise interface you can use instead of the callback interface.