I've been learning about ES6 promises in Node (7.4.0) because I want to apply them to handle serial communications. I made a promise that is an aggregate of a number of smaller promises that allows me to use a sender, an EventListener and a timeout to serialize communication with a device. However, I don't quite understand .then() chaining, because I need to add in some additional closures that look different from what i see in many examples, which leads me to believe I am misunderstanding something fundamental. Consider this function (I removed all the prototype/this. code to make it smaller):
function sendAck(command, ack, timeout) {
return new Promise((resolve, reject) => {
if (gReady === undefined) reject('not ready');
// each of these three functions returns a promise
let sendPromise = createSend(command);
let ackPromise = createAck(ack);
let timeoutPromise = createTimeout(timeout);
// p1 = we hear a response, or timeout waiting for one
let p1 = Promise.race([ackPromise, timeoutPromise]);
// both p1 -and- send function need to resolve
let p2 = Promise.all([p1, sendPromise]);
p2.then(values => resolve(values)).catch(err => {
localCleanup(); /// otherwise just return p2, but need to do this
reject(err)
});
}
}
Now when I try to chain a bunch of sendAck()s with then, I find that this usage fails as they all execute at once:
sendAck('init', 'pass', 3000)
.then(sendAck('enable a', 'pass', 3000))
.then(sendAck('enable b', 'pass', 3000))
:
So I have to wrap each in a closure to make it work, since the closure is evaluated on the then() rather than the function being evaluated by the JS interpreter. Which feels like I'm missing something very important because it looks awkward:
sendAck('init', 'pass', 3000)
.then(() => { return sendAck('enable a', 'pass', 3000) })
.then(() => { return sendAck('enable b', 'pass', 3000) })
:
I'm confusing because I see other examples online where .then() contains a function that returns a promise, like...
.then(onHttpRequest)
Which clearly is different from
.then(onHttpRequest())
It just seems weird to have to chain .then() with closures. Am I doing this correctly and just not used to it, or am I missing something?
Thanks in advance.
PT
EDIT: As discussed below, there are no closures in my issue, just anonymous functions.