How to use the ember-concurrency.task function in ember-concurrency

To help you get started, we’ve selected a few ember-concurrency examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github usecanvas / canvas-editor / addon / components / ui-list-filter / component.js View on Github external
const { computed, on, A } = Ember;

export default Ember.Component.extend({
  layout,
  /* eslint-disable prefer-reflect */
  results: computed(_ => A([])),

  setupResults: on('init', 'willDestroyElement', function() {
    this.get('results').setObjects([]);
    this.get('onResolveFilter')([]);
  }),

  onResolveFilter: Ember.K,

  handleValueChange: task(function *() {
    const value = this.get('value');
    const results = yield this.get('onFilter')(value);
    this.set('results', results);
    this.get('onResolveFilter')(results);
  }).observes('value').keepLatest()
});
github TryGhost / Ghost-Admin / app / controllers / editor.js View on Github external
// detection errors
    savePost: task(function* () {
        try {
            return yield this._savePost.perform();
        } catch (error) {
            if (error) {
                let status = this.get('post.status');
                this._showErrorAlert(status, status, error);
            }

            throw error;
        }
    }).group('saveTasks'),

    // convenience method for saving the post and performing post-save cleanup
    _savePost: task(function* (options) {
        let {post} = this;

        yield post.save(options);

        // remove any unsaved tags
        // NOTE: `updateTags` changes `hasDirtyAttributes => true`.
        // For a saved post it would otherwise be false.
        post.updateTags();
        this._previousTagNames = this._tagNames;

        // update the scratch property if it's `null` and we get a blank mobiledoc
        // back from the API - prevents "unsaved changes" modal on new+blank posts
        if (!post.scratch) {
            post.set('scratch', JSON.parse(JSON.stringify(post.get('mobiledoc'))));
        }
github hashicorp / vault / ui / lib / core / addon / components / info-table-item-array.js View on Github external
wildcardInDisplayArray: false,
  store: service(),
  displayArrayAmended: computed('displayArray', function() {
    let { displayArray } = this;
    if (!displayArray) {
      return;
    }
    if (displayArray.length >= 10) {
      // if array greater than 10 in length only display the first 5
      displayArray = displayArray.slice(0, 5);
    }

    return displayArray;
  }),

  checkWildcardInArray: task(function*() {
    if (!this.displayArray) {
      return;
    }
    let filteredArray = yield this.displayArray.filter(item => isWildcardString(item));
    this.set('wildcardInDisplayArray', filteredArray.length > 0 ? true : false);
  }).on('didInsertElement'),

  fetchOptions: task(function*() {
    if (this.isLink && this.modelType) {
      let queryOptions = {};

      if (this.backend) {
        queryOptions = { backend: this.backend };
      }

      let options = yield this.store.query(this.modelType, queryOptions);
github hashicorp / vault-service-broker / vendor / github.com / hashicorp / vault / ui / app / components / auth-form.js View on Github external
let methodsToShow = this.get('methodsToShow');
    return hasMethodsWithPath ? methodsToShow.concat(BACKENDS) : methodsToShow;
  }),

  hasMethodsWithPath: computed('methodsToShow', function() {
    return this.get('methodsToShow').isAny('path');
  }),
  methodsToShow: computed('methods', function() {
    let methods = this.get('methods') || [];
    let shownMethods = methods.filter(m =>
      BACKENDS.find(b => get(b, 'type').toLowerCase() === get(m, 'type').toLowerCase())
    );
    return shownMethods.length ? shownMethods : BACKENDS;
  }),

  unwrapToken: task(function*(token) {
    // will be using the token auth method, so set it here
    this.set('selectedAuth', 'token');
    let adapter = this.get('store').adapterFor('tools');
    try {
      let response = yield adapter.toolAction('unwrap', null, { clientToken: token });
      this.set('token', response.auth.client_token);
      this.send('doSubmit');
    } catch (e) {
      this.set('error', `Token unwrap failed: ${e.errors[0]}`);
    }
  }),

  fetchMethods: task(function*() {
    let store = this.get('store');
    try {
      let methods = yield store.findAll('auth-method', {
github hummingbird-me / hummingbird-client / app / components / modals / block-user.js View on Github external
import Component from '@ember/component';
import { get } from '@ember/object';
import { assert } from '@ember/debug';
import { inject as service } from '@ember/service';
import { isPresent } from '@ember/utils';
import { task } from 'ember-concurrency';
import errorMessages from 'client/utils/error-messages';

export default Component.extend({
  notify: service(),
  store: service(),

  blockUser: task(function* () {
    const block = get(this, 'store').createRecord('block', {
      user: get(this, 'session.account'),
      blocked: get(this, 'user')
    });

    yield block.save().then(() => {
      this.$('.modal').modal('hide');
      get(this, 'notify').info(`You have blocked ${get(this, 'user.name')}`);
    }).catch(err => (
      get(this, 'notify').error(errorMessages(err))
    ));
  }).drop(),

  init() {
    this._super(...arguments);
    assert('You must pass a user into the `block-user` component.', isPresent(get(this, 'user')));
github hummingbird-me / hummingbird-client / app / components / groups / dashboard / members / invite-list.js View on Github external
export default Component.extend(Pagination, {
  algolia: service(),
  notify: service(),
  store: service(),
  invites: concat('getInvitesTask.last.value', 'paginatedRecords'),

  init() {
    this._super(...arguments);
    get(this, 'getInvitesTask').perform();
  },

  canInvite: computed('inviteUser', 'inviteUserTask.isIdle', function() {
    return get(this, 'inviteUser') && get(this, 'inviteUserTask.isIdle');
  }).readOnly(),

  getInvitesTask: task(function* () {
    return yield this.queryPaginated('group-invite', {
      filter: { group: get(this, 'group.id'), status: 'pending' },
      include: 'user'
    });
  }),

  searchUsersTask: task(function* (query) {
    yield timeout(250);
    const index = yield this.get('algolia.getIndex').perform('users');
    const response = yield index.search(query, {
      attributesToRetrieve: ['id', 'name'],
      hitsPerPage: 10
    });
    return response.hits || [];
  }).restartable(),
github travis-ci / travis-web / app / components / billing / trial.js View on Github external
subscription: reads('account.subscription'),
  accountTrial: reads('account.trial'),
  isGithubTrial: and('subscription.isGithub', 'accountTrial.hasActiveTrial'),
  newTrial: null,
  trial: computed('accountTrial', 'newTrial', function () {
    return !this.newTrial ? this.accountTrial : this.newTrial;
  }),
  isBuildLessThanEleven: lt('trial.buildsRemaining', 11),
  isBuildFinished: equal('trial.buildsRemaining', 0),
  isBuildRemaining: not('isBuildFinished'),
  showBuildRunningOutBanner: and('isBuildRemaining', 'isBuildLessThanEleven'),
  hasNoSubscriptionPermissions: not('account.hasSubscriptionPermissions'),
  hasNoActiveTrial: not('trial.hasActiveTrial'),

  activateTrial: task(function* () {
    const trial = this.store.createRecord('trial', {
      owner: this.account,
      type: this.account.isOrganization === true ? 'organization' : 'user'
    });

    try {
      const saved = yield trial.save();
      saved.set('status', 'new');
      saved.set('buildsRemaining', 100);
      this.set('newTrial', saved);
      yield this.accounts.fetchTrials.perform();
    } catch (e) {
      this.flashes.error('There was an error activating trial.');
      this.raven.logException(e);
    }
  }).drop(),
github ilios / frontend / app / components / course-rollover.js View on Github external
selectedCohorts: null,

  keyUp(event) {
    const keyCode = event.keyCode;
    const target = event.target;

    if ('text' !== target.type) {
      return;
    }

    if (13 === keyCode) {
      this.get('save').perform();
    }
  },

  save: task(function * (){
    this.set('isSaving', true);
    yield timeout(10);
    this.send('addErrorDisplaysFor', ['title', 'selectedYear']);
    let {validations} = yield this.validate();

    if (validations.get('isInvalid')) {
      this.set('isSaving', false);
      return;
    }
    const commonAjax = this.get('commonAjax');
    const courseId = this.get('course.id');
    const expandAdvancedOptions = this.get('expandAdvancedOptions');
    const year = this.get('selectedYear');
    const newCourseTitle = this.get('title');
    const selectedCohortIds = this.get('selectedCohorts').mapBy('id');
    let newStartDate = moment(this.get('startDate')).format('YYYY-MM-DD');
github cardstack / cardstack / packages / tools / addon / components / cs-create-menu.js View on Github external
import Component from '@ember/component';
import layout from '../templates/components/cs-create-menu';
import { transitionTo } from '../private-api';
import { task } from 'ember-concurrency';
import injectOptional from 'ember-inject-optional';

export default Component.extend({
  layout,
  classNames: ['cs-create-menu'],
  tools: service('cardstack-tools'),
  store: service(),
  cardstackRouting: injectOptional.service(),

  availableTypes: computed(function() { return []; }),

  loadAvailableTypes: task(function * () {
    let creatableTypes = this.get('tools.creatableTypes');
    if (!creatableTypes || !creatableTypes.length) { return; }

    let types = yield this.get('store').query('content-type', { page: { size: 50 }, filter: { 'id' : { exact: creatableTypes } } });
    this.set('availableTypes', types);
  }).on('init'),

  actions: {
    create(which) {
      let { name, params, queryParams } = this.get('cardstackRouting').routeForNew(which.id, this.get('tools.branch'));
      transitionTo(getOwner(this), name, params.map(p => p[1]), queryParams);
      this.get('tools').setActivePanel('cs-composition-panel');
      this.get('tools').setEditing(true);
    }
  }
});
github apache / incubator-pinot / thirdeye / thirdeye-frontend / app / pods / rca / controller.js View on Github external
import { computed } from '@ember/object';
import { oneWay } from '@ember/object/computed';
import Controller from '@ember/controller';
import { task, timeout } from 'ember-concurrency';
import { selfServeApiCommon } from 'thirdeye-frontend/utils/api/self-serve';
import { checkStatus } from 'thirdeye-frontend/utils/utils';

export default Controller.extend({
  primaryMetric: oneWay('model'),
  mostRecentSearch: null,

  /**
   * Ember concurrency task that triggers the metric autocomplete
   */
  searchMetrics: task(function* (metric) {
    yield timeout(600);

    /**
     * Necessary headers for fetch
     */
    const headers = {
      method: "GET",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Cache': 'no-cache'
      },
      credentials: 'include'
    };

    return fetch(selfServeApiCommon.metricAutoComplete(metric), headers)