Search code examples
javascriptjquerypromisebluebird

bluebird promise and events


I have to refactor existing JavaScript code. This include a validation library and some editors. And I am new with working with Promise. The old code was (following simplified):

$this.bind("validation.validation", function (event, params) {
  var value,
      errorsFound = [];
  value = params.editor.getValue();
  $.each(validators, function (i, validator) {
    if (validator.validate(value)) {
      errorsFound.push(validator.getErrMsg());
    }
  });
  return errorsFound;
});

The event validation.validation is triggered in many places. The returned array contains error messages. The editors are completly new and don't return a value with getValue() but return a Promise.

$this.bind("validation.validation", function (event, params) {
  var errorsFound = [];
  params.editor.read().then(function (value) {
    $.each(validators, function (i, validator) {
      if (validator.validate(value)) {
        errorsFound.push(validator.getErrMsg());
      }
    });
    return errorsFound;
  });
  // return ??? what ???
});

I would like, if possible, to avoid a complete refactoring of this validation code. But how can the event handler return something that is got asynchronous? Is this even possible?

Thank you


Solution

  • You would need to return the Promise. Then the calling code would need to understand Promises and get the value after the Promise resolves. Otherwise, there isn't a lot that can be done. Without something like Async/Await in ES6.