Consider this code:
function openSocket() { /* returns a promise for a socket */ }
function sendMessage1(socket) { /* sends 1st message, returns a promise for a response */ }
function sendMessage2(socket) { /* sends 2nd message, returns a promise for a response */ }
function cleanup(socket) { /* closes the socket */ }
function updateUI() {}
function showError(error) {}
openSocket()
.then(sendMessage1)
.then(sendMessage2)
.then(cleanup)
.then(updateUI)
.catch(showError);
Note that both sendMessage*()
functions accept socket as a parameter. But only first one will get this, because only the first one will get the resolved value from openSocket()
.
I can go around this by using a variable in the outer scope, i.e. assign the socket once it's resolved, and then use it in sendMessage2()
, but it seems a bit hacky and dirty.
Also, I know I can use some library support, like described in this answer regarding Q.
I'm looking for a canonical way of designing this code, which:
- would not require any variables in outer scope
- would not rely on 3rd party promise libraries (should be based on ES6 promises)
Is there some way to accomplish that? Or would that be better to refactor my code to make it easier?