Ember.JS concurrency task, perform() is not a function

1.1k Views Asked by At

I was trying to convert a function over to a task. Here is the original code:

Call:

this.socketConnect(endpoint, token);

Function:

socketConnect = async (token, endpoint) => {
        this.socket = new WebSocket(endpoint + '?auth=' + token);

        this.socket.addEventListener('open', () => {
                this.socket.addEventListener('message', event => this.handleMessage(event));

                this.socket.addEventListener('close', event => this.retryConnection(event, endpoint));

        });
    }

I've been following structure on implementing Ember tasks. It all compiles with no issue, however when it gets called, it outputs that this.socketConnect(...) is not a function. Before hand I didn't have the return below and it output that this.socketConnect wasn't a function. Here is my current code for a task.

Import:

import { task } from 'ember-concurrency';

Call:

this.socketConnect(endpoint, authToken).perform();

Function:

@task *socketConnect(endpoint, token) {
        yield async () => {
            this.socket = new WebSocket(endpoint + '?auth=' + token);
            this.socket.addEventListener('open', () => {
                this.socket.addEventListener('message', event => this.handleMessage(event));

                this.socket.addEventListener('close', event => this.retryConnection(event, endpoint));
            });

            return;
        };

    }

New to this, so I'm guessing there's something small I'm missing. It matches other uses. Also if anyone could help on the benefits of switching a websocket generation function to a task? Any help would be appreciated, thank you.

1

There are 1 best solutions below

3
jrjohnson On

The @task decorator isn't part of the official ember-concurency package yet. The official version lives in ember-concurrency-decorators for now. You'll need to ember install ember-concurrency-decorators

and then you can do

import { task } from 'ember-concurrency-decorators';

To use it.

Alternatively you can use a different syntax if you don't want another dependency.

import { task } from 'ember-concurrency';

class Foo {
  @(task(function*() {
    // ...
  }).restartable())
  doStuff;

  executeTheTask() {
    this.doStuff.perform();
  }
}

To call the task the syntax is: this.socketConnect.perform(endpoint, authToken);

As you're not calling socketConnect directly, you want to call the method that ember concurrency generates for you.