Are JavaScript ES6 Classes of any use with asynchronous code bases?

后端 未结 4 1037
离开以前
离开以前 2020-12-01 01:22

What can ES6 Classes provide, as a pattern of organization, to asynchronous code. Below is an example with ES7 async/await, can an ES6-class have an asynchronous method, or

4条回答
  •  时光说笑
    2020-12-01 01:42

    ECMAScript 2017 is intended to be classes of async methods.

    Invoking another async or promise-returning function is a one-liner!

    The highly expressive code reads without interruption top to bottom regardless of deferred execution

    If you have callbacks, alternative error handlers, parallel execution or other unmet needs, instantiate promises in function body. It is better to have code in the function body rather than in a promise executor, and note that there is no try-catch wrapping callback code: do next-to-nothing there.

    The async method can return a promise, a regular value, or throw

    The callback apis that Node.js people used to love, we will now hate with a passion: they must all be wrapped in promises

    The beauty of async/await is that errors bubble up implicitly

    class MyClass {
      async doEverything() {
        const sumOfItAll = await http.scrapeTheInternet() +
          await new Promise((resolve, reject) =>
            http.asyncCallback((e, result) => !e ? resolve(result) : reject(e)))
        return this.resp = sumOfItAll
      }
    }
    

    If limited to ECMAScript 2015 and no async, return promise values:

    class ES2015 {
      fetch(url) {
        return new Promise((resolve, reject) =>
          http.get(url, resolve).on('error', reject))
          .then(resp => this.resp = resp) // plain ECMAScript stores result
          .catch(e => { // optional internal error handler
            console.error(e.message)
            throw e // if errors should propagate
          })
      }
    }
    

    This ECMAScript 2015 version is what you are really asking about, any desired behavior can be coded up using the returned promise construct.

    If you really, really want to execute promises in the constructor, it is a good idea to pass in then-catch functions or provide some callback construct so that consumers can take action on promise fulfillment or rejection. In the constructor, it is also good practice to wait for nextTick/.then before doing real work.

    Every promise needs a final catch or there will be trouble

提交回复
热议问题