2

Hey I am writing a small lib Splunk to use the ES6 feature Async/Await to communicate with the backend. But when I set the Arrow Function in the define statement define([], async () => { await smth }); it seems that it is not invoked anymore.

Here my code so far:

controller.js

require([
  '../app/splunk-async/splunk-async',
], async (SplunkAsync) => {
  const SA = new SplunkAsync();

  const data = await SA.get('/services/authentication/users');
  console.log(data)
});

splunk-async.js

//# sourceURL=splunk-async.js

define(['splunkjs/mvc'], (mvc) => 
  class asyncSplunk {
    constructor () {
      this._service = mvc.createService();
    }

    /**
     * 
     * @param {String} uri 
     */
    get (uri) {
      return new Promise((resolve, reject) => {
        const service = this._service;

        service.get(uri)          
          .done(res => resolve(res))
          .fail((data, status, err) => reject(data, status, err));
      });
    }
  }
);

Does anyone has a solution? Thanks :)

Edit 1:

Thank you for your responses. I've tried all your suggestions. But none of them seem to work. When I wrap everything in try/catch nothing is "catched". The function Promise.promisify() does not exit. It seems that I have to tell the define function, that its body is async which I tried: async () => {}.

Any more suggestions?

bmacher
  • 51
  • 1
  • 7
  • 1
    It should still get invoked, but you shouldn't do that even if it does. `require` doesn't do anything with the promise your `async` function returns, meaning errors are completely unhandled. If you do this, be sure to wrap the entire function body in `try`/`catch` and handle errors inline. – T.J. Crowder Jan 29 '19 at 15:59
  • To tidy things up, I would make your `require` loader into a Promise loader.. you could then do code like -> `const [$] = await prequire(["jquery"])` etc. Your current error handler could then be used,. No need for the `try / catch` like @T.J.Crowder mentions. – Keith Jan 29 '19 at 16:48
  • Btw, avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 29 '19 at 18:37
  • I tried all but nothing seem to work. – bmacher Jan 30 '19 at 07:41

0 Answers0