I'm retrieving a form (via XMPP, XEP-0004), creating an interactive form dialog for it, then submitting the form when the dialog is closed.
The code (roughly approximated for simplicity):
function form(name, callback) {
server.getForm(name, function(response) {
callback(response.formFields, function (data) {
server.submitForm(name, data);
});
});
}
function main() {
form('example', function(fields, callback) {
var dialog = ui.formDialog(fields);
dialog.addButton('submit', function(data) {
callback(data);
});
dialog.show();
});
}
Note how the caller and callee exchange callbacks - in one direction, for the fields retrieved from the server; in the other, for the user-submitted data.
I've recently discovered JS Promises and I'd like to know if they could replace the callbacks more elegantly.
I got as far as:
function form(name) {
return new Promise((resolve, reject) => {
server.getForm(
name,
(response) => { resolve(response.formFields) },
reject
);
});
}
function main() {
form('example').then((fields) => {
var dialog = ui.formDialog(fields);
dialog.addButton('submit', /* ... */);
});
}
But now I'm stuck, because I have no way to pass the submit button's event back to the form()
call.
I can't simply create a Promise for the dialog either, because I'd have to create that promise first in order to pass it to form()
, but I need the promise returned by form()
to be resolved before I can create the dialog. There's a sort of bootstrap problem.
Is there some way to use promises here, or should I stick with passing callbacks back and forth?