How to use the q.defer function in q

To help you get started, we’ve selected a few q 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 vbudhram / fantasy-football-io / utils / yahooUtils.js View on Github external
getTeams: function (username, password) {
            var resultQ = q.defer();

            login(username, password).then(function (data) {

                console.log('Getting Yahoo teams for username/password = ' + username + '/*****');

                // Load html from fantasy football screen to extract team names
                var $ = cheerio.load(data.body);

                var teamLinks = $('.Fz-sm').find('a');

                var promises = [];
                for (var i = 0; i < teamLinks.length; i++) {
                    var teamLink = teamLinks[i];
                    if (teamLink.attribs.href !== undefined && teamLink.attribs.href.indexOf('/f1/') > -1 && (i % 2 === 0)) {
                        var teamUrl = 'http://football.fantasysports.yahoo.com' + teamLink.attribs.href;
                        promises.push(getTeam(teamUrl, data.cookieJar));
github acoustic-content-samples / wchtools-cli / authoring-api / lib / assetsREST.js View on Github external
}
                        } else if (!isOrphanedResource) {
                            // Creating new asset metadata. Fernando web asset or create-only.
                            restObject.getUpdateRequestOptions(context, opts)
                                .then(function (reqOptions) {
                                    reqOptions.body = requestBody;
                                    restObject._postAssetMetadata(context, opts, reqOptions, deferred, createOnly);
                                });
                        } else {
                            // This is an orphaned resource, there is no content metadata so just resolve
                            deferred.resolve(body);
                        }
                    }
                };

                const headDeferred = Q.defer();
                const headResponsePromise = headDeferred.promise;
                if (useResourcePUT) {
                    // Before a PUT, do HEAD request to see if the resource already exists with the same MD5 hash.
                    restObject.getDownloadRequestOptions(context, opts).then(function (headReqOptions) {
                        headReqOptions.uri = restObject._appendURI(headReqOptions.uri, resourceId) + "?bypass-cache=" + Date.now();
                        request.head(headReqOptions, function(headErr, headRes, headBody) {
                            if (!headErr && headRes && headRes.statusCode && headRes.statusCode === 200 && headRes.headers && headRes.headers.etag) {
                                const etag = headRes.headers.etag.substring(1, headRes.headers.etag.length-1);
                                if (hashes.compareMD5Hashes(resourceMd5, etag)) {
                                    // The hashes are equal, the resource already exists with a matching MD5.
                                    headDeferred.resolve(false);
                                } else {
                                    // A resource already exists using the requested resource id, but with a different md5 hash.
                                    // This should only ever happen for a content resource, since web resources use the md5 hash of the binary content as part of the resource id.
                                    useResourcePUT = false;
                                    restObject.getResourcePOSTOptions(context, pathname, rOpts).then(function (postRequestOptions) {
github appium / appium / test / helpers / session.js View on Github external
module.exports.initSession = function (desired, opts) {
  desired = desired || {};
  opts = opts || {};

  var deferred = Q.defer(),
      browser,
      initialized;

  wd.addPromiseChainMethod('clickBack', function () {
    var backEl;
    return this.elementByNameOrNull('Back')
    .then(function (el) {
      if (el) {
        backEl = el;
        return el.isDisplayed();
      } else return false;
    })
    .then(function (isDisplayed) {
      if (isDisplayed) {
        return backEl.click();
      }
github twilio / twilio-node / lib / rest / ipMessaging / v2 / service / channel / message.js View on Github external
MessageListInstance.page = function page(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'Order': _.get(opts, 'order'),
      'PageToken': opts.pageToken,
      'Page': opts.pageNumber,
      'PageSize': opts.pageSize
    });

    var promise = this._version.page({uri: this._uri, method: 'GET', params: data});

    promise = promise.then(function(payload) {
      deferred.resolve(new MessagePage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });
github ghaiklor / generator-sails-rest-api / generators / app / templates / api / services / mailer / MandrillMailer.js View on Github external
send: function () {
    var defer = Q.defer();

    this.getClient().messages.send({
      message: {},
      async: true,
      ip_pool: "Main Pool",
      send_at: Date.now()
    }, function (result) {
      defer.resolve(result);
    }, function (error) {
      defer.reject(error);
    });

    return defer.promise;
  }
});
github juliemr / protractor-demo / howtos / setFirefoxProfile / helper.js View on Github external
exports.getFirefoxProfile = function() {
  var deferred = q.defer();

  var firefoxProfile = new FirefoxProfile();
  firefoxProfile.setPreference('browser.newtab.url', 'https://www.angularjs.org');
  firefoxProfile.encoded(function(encodedProfile) {
    var multiCapabilities = [{
      browserName: 'firefox',
      firefox_profile : encodedProfile
    }];
    deferred.resolve(multiCapabilities);
  });

  return deferred.promise;
};
github twilio / twilio-node / lib / rest / autopilot / v1 / assistant / defaults.js View on Github external
DefaultsContext.prototype.fetch = function fetch(callback) {
  var deferred = Q.defer();
  var promise = this._version.fetch({uri: this._uri, method: 'GET'});

  promise = promise.then(function(payload) {
    deferred.resolve(new DefaultsInstance(this._version, payload, this._solution.assistantSid));
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};
github ionic-team / ionic-app-lib / lib / browser.js View on Github external
Browser.downloadCordova40x = function downloadCordova40x(appDirectory) {
  var q = Q.defer();

  var crosswalkEngineUnzipName = ['cordova-android-', cordovaAndroidVersion].join('');
  var downloadUrl = ['https://github.com/driftyco/cordova-android/archive/', cordovaAndroidVersion, '.zip'].join('');

  var tempZipFilePath = path.join(appDirectory, 'engine');
  var cordovaAndroid4Path = path.join(tempZipFilePath, crosswalkEngineUnzipName, 'bin');
  var android4BinPath = path.join(cordovaAndroid4Path, 'templates', 'cordova');

  if (fs.existsSync(path.join(tempZipFilePath, crosswalkEngineUnzipName))) {

    Browser.setPermissionsForFolder(cordovaAndroid4Path);
    Browser.setPermissionsForFolder(android4BinPath);

    q.resolve();
    return;
  }
github lwmqn / qnode / lib / smartobject.js View on Github external
SmartObject.prototype.dump = function (callback) {
    var self = this,
        deferred = Q.defer(),
        excludeKeys = [ 'name', 'node', 'attrs' ],
        dumpAllProms = [],
        dumped = {};

    _.forOwn(this, function (n, oid) {
        if (!_.isFunction(n) && !_.includes(excludeKeys, oid)) {
            dumpAllProms.push(
                self.dumpIObject(oid).then(function (data) {
                    dumped[mutils.oidNumber(oid)] = data;
                })
            );
        }
    });

    Q.all(dumpAllProms).done(function () {
        deferred.resolve(dumped);
github BrianPetkovsek / discord-youtube / main.js View on Github external
function download(uri, filename) {
	var url = require('url');
	var Q = require('q');
	var fs = require('fs'); 
    var protocol = url.parse(uri).protocol.slice(0, -1);
    var deferred = Q.defer();
    var onError = function (e) {
        fs.unlink(filename);
        deferred.reject(e);
    }
    require(protocol).get(uri, function(response) {
        if (response.statusCode >= 200 && response.statusCode < 300) {
            var fileStream = fs.createWriteStream(filename);
            fileStream.on('error', onError);
            fileStream.on('close', deferred.resolve);
            response.pipe(fileStream);
        } else if (response.headers.location) {
            deferred.resolve(download(response.headers.location, filename));
        } else {
            deferred.reject(new Error(response.statusCode + ' ' + response.statusMessage));
        }
    }).on('error', onError);