}).then(function(response) { return rsvp.Promise.resolve(response); }).catch(function(err) {
exports.lookup = function(pkg) { return Promise.resolve() // load the version map .then(function() { if (versionCache[pkg.package]) return versionCache[pkg.package]; cli.log('info', 'Checking versions for `' + pkg.name + '`'); return new Promise(function(resolve, reject) { var promise = _pkg.loadEndpoint(pkg.endpoint).getVersions(pkg.package, resolve, reject); if (promise) promise.then(resolve, reject); }) .then(function(versions) { var versionMap = {}; for (var v in versions) { var version = v.substr(0, 1) == 'v' ? v.substr(1) : v; var semverMatch = version.match(semver.semverRegEx); // non stable versions marked if (!semverMatch || !semverMatch[3] || !semverMatch[1] || semverMatch[4]) versionMap[v] = { stable: false, hash: versions[v] }; else versionMap[version] = { stable: true, hash: versions[v], original: v }; } // save the version cache return versionCache[pkg.package] = versionMap; }); }) // get the version match .then(function(versionMap) { var rangeVersion = pkg.version.substr(0, 1) == '^' ? pkg.version.substr(1) : pkg.version; var rangeMatch = rangeVersion.match(semver.semverRegEx); // tag or prerelease -> match exact or nothing if (pkg.version && (!rangeMatch || rangeMatch[4])) { if (versionMap[rangeVersion]) return { version: rangeVersion, hash: versionMap[rangeVersion] }; return null; } var versionList = []; for (var v in versionMap) versionList.push(v); versionList = versionList.filter(function(v) { return versionMap[v].stable; }); versionList.sort(semver.compare); // find highest stable match // latest is empty string for (var i = versionList.length - 1; i >=0; i--) { if (!pkg.version || semver.match(pkg.version, versionList[i])) { return { version: versionList[i], hash: versionMap[versionList[i]] }; } } // if we asked for latest, and nothing stable found, use master if (!pkg.version) { if (versionMap.master) return { version: 'master', hash: versionMap.master }; } }) // return the lookup .then(function(lookupObj) { if (!lookupObj) throw 'No version match found for `' + pkg.exactName + '`'; var lookup = new Package(pkg.name + '@' + lookupObj.version); lookup.hash = lookupObj.hash; return lookup; }); }
// we want the build to wait first for the current build, then the timeout function timoutThenBuild() { return timeout.then(build); }
.then((types) => { var promises = types.map(type => this.getAllStates(type)); return Promise.all(promises).then(_.flatten); });
exports.download = function(pkg, jspmPackages, override, force) { var downloadDir = path.resolve(jspmPackages, pkg.endpoint, pkg.exactPackage); // if not forcing, and we have a hash, check if the download folder is fresh // no hash means we have skipped a lookup as we are using an existing file // so we are fresh by default // forcing means always not fresh return ((force || !pkg.hash) ? Promise.resolve(force ? false : true) : isFresh(downloadDir, pkg.hash)) // if not fresh, simultaneously check for an override and do the download .then(function(fresh) { pkg.fresh = fresh; if (fresh) return false; ui.log('info', 'Downloading `' + pkg.exactName + '`'); return Promise.all([ override ? Promise.resolve(override) : _pkg.checkOverride(pkg.exactName, false), Promise.resolve(downloadDir) // ensure the download directory exists .then(asp(mkdirp)) // clear the directory .then(function() { return asp(rimraf)(downloadDir); }) .then(function() { return asp(fs.mkdir)(downloadDir) }) // do the download .then(function() { return new Promise(function(resolve, reject) { var exactVersion = versionCache[pkg.package][pkg.version].original || pkg.version; var promise = _pkg.loadEndpoint(pkg.endpoint).download(pkg.package, exactVersion, pkg.hash, downloadDir, resolve, reject); if (promise) promise.then(resolve, reject); }); }) // if the download defines the package.json use that // otherwise load the package.json .then(function(pjson) { if (pjson) return pjson; return asp(fs.readFile)(path.resolve(downloadDir, 'package.json')) .then(function(data) { try { return JSON.parse(data); } catch(e) {} }, function() {}); }) ]) // apply the overrides to get a final package.json .then(function(pjsons) { var pjson = pjsons && pjsons[1] || {}; var override = pjsons && pjsons[0]; // apply the jspm internal overrides first if (pjson.jspm) extend(pjson, pjson.jspm); if (override) extend(pjson, override); // parse the dependencies pjson.dependencies = config.parseDependencies(pjson.dependencies, pjson.registry); // having parsed, note now that we are in the jspm registry form pjson.registry = 'jspm'; // if there is a "browser" object, convert it into map config for browserify support if (typeof pjson.browser == 'object') { pjson.map = pjson.map || {}; for (var b in pjson.browser) { var mapping = pjson.browser[b]; if (b.substr(b.length - 3, 3) == '.js') b = b.substr(0, b.length - 3); if (mapping.substr(mapping.length - 3, 3) == '.js') mapping = mapping.substr(0, mapping.length - 3); // local maps not supported since this affects the external // interface for all other modules // only way to implement is through a module alias replacement // may be worth considering at some point if (b.substr(0, 2) == './') continue; pjson.map[b] = pjson.map[b] || mapping; } } return pjson; }) // apply build operations from the package.json .then(function(pjson) { // don't build in dependencies var pjsonObj = extend({}, pjson); delete pjsonObj.dependencies; return build.buildPackage(downloadDir, pjsonObj) .then(function() { return pjson; }); }) // save the final calculated package.json in place .then(function(pjson) { return asp(fs.writeFile)(path.resolve(downloadDir, 'package.json'), JSON.stringify(pjson, null, 2)) .then(function() { return pjson; }); }) // create the main entry point .then(function(pjson) { var lastNamePart = pkg.name.split('/').pop().split(':').pop(); var main = typeof pjson.browser == 'string' && pjson.browser || typeof pjson.main == 'string' && pjson.main; if (main) { if (main.substr(0, 2) == './') main = main.substr(2); if (main.substr(main.length - 3, 3) == '.js') main = main.substr(0, main.length - 3); } main = main || 'index'; // try the package.json main return new Promise(function(resolve, reject) { fs.exists(path.resolve(downloadDir, main.substr(main.length - 3, 3) != '.js' ? main + '.js' : main), resolve); }) .then(function(exists) { if (exists) return true; main = lastNamePart; return new Promise(function(resolve, reject) { fs.exists(path.resolve(downloadDir, main.substr(main.length - 3, 3) != '.js' ? main + '.js' : main), resolve); }) }) .then(function(exists) { // create the main pointer var mainFile = path.resolve(downloadDir, '../' + lastNamePart + '@' + pkg.version + '.js'); return asp(fs.writeFile)(mainFile, 'export * from "' + pkg.exactName + '/' + main + '";'); }) .then(function() { // finally add the .jspm-hash // NB should move this into full tree completion, but is tricky due to async edge cases return asp(fs.writeFile)(path.resolve(downloadDir, '.jspm-hash'), pkg.hash) }) .then(function() { return pjson; }) }) }) .then(function(pjson) { if (pjson) return pjson; // if fresh, load the package.json return asp(fs.readFile)(path.resolve(downloadDir, 'package.json')) .then(function(data) { try { return JSON.parse(data); } catch(e) {} }, function() {}); }) // return the dependencies .then(function(pjson) { return pjson && pjson.dependencies || {}; }); }
if (transitionAfterSave) { let transitionArgs = [ transitionAfterSave ]; if (this.get('transitionWithModel')) { transitionArgs.push(record.get(this.getWithDefault('modelIdentifier', 'id'))); } this.transitionToRoute.apply(this, transitionArgs); } }, saveModel (model) { const _model = model || this.get('model'); if (!_model) { return Promise.resolve(); } if (get(_model, 'length')) { return map(_model, this.saveModel.bind(this)); } this.ajaxStart(); let invalid = this._validateModel(_model); if (invalid) { let requireFieldDescriptors = get(this, 'requireFieldDescriptors'), invalidMessage = 'You must specify these fields: ' + invalid.map(field => { return requireFieldDescriptors ? requireFieldDescriptors[field] || field : field; }).join(', ');
sinon.stub(async, "resolve", function(v) { return RSVP.Promise.resolve(v); });
import { once } from '@ember/runloop'; import { Promise as EmberPromise } from 'rsvp'; import Service, { inject as service } from '@ember/service'; import { task } from 'ember-concurrency'; export default Service.extend({ store: service(), init() { this.toFetch = {}; return this._super(...arguments); }, fetch(job) { if (job._config) { return EmberPromise.resolve(job._config); } if (this.toFetch[job.id]) { return this.toFetch[job.id].promise; } else { let data = this.toFetch[job.id] = { job }; let promise = new EmberPromise((resolve, reject) => { data.resolve = resolve; }); data.promise = promise; once(this, 'flush'); return promise; } }, fetchTask: task(function* () {
export function _query(adapter, store, modelName, query, recordArray, options) { if (DEBUG) { incrementRequestCount(); } let modelClass = store.modelFor(modelName); // adapter.query needs the class let promise; let createRecordArray = adapter.query.length > 3 || (adapter.query.wrappedFunction && adapter.query.wrappedFunction.length > 3); if (createRecordArray) { recordArray = recordArray || store.recordArrayManager.createAdapterPopulatedRecordArray(modelName, query); promise = Promise.resolve().then(() => adapter.query(store, modelClass, query, recordArray, options) ); } else { promise = Promise.resolve().then(() => adapter.query(store, modelClass, query)); } let label = `DS: Handle Adapter#query of ${modelName}`; promise = guardDestroyedStore(promise, store, label); return promise.then( adapterPayload => { let serializerToken = heimdall.start('initial-serializerFor-lookup'); let serializer = serializerForAdapter(store, adapter, modelName); heimdall.stop(serializerToken); let normalizeToken = heimdall.start('finders#_query::normalizeResponseHelper'); let payload = normalizeResponseHelper( serializer, store, modelClass, adapterPayload, null, 'query' ); heimdall.stop(normalizeToken); let internalModels = store._push(payload); assert( 'The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.', Array.isArray(internalModels) ); if (recordArray) { recordArray._setInternalModels(internalModels, payload); } else { recordArray = store.recordArrayManager.createAdapterPopulatedRecordArray( modelName, query, internalModels, payload ); } return recordArray; }, null, `DS: Extract payload of query ${modelName}` ); }
.then(function() { // set dependency version range to semver-compatible when none provided if (!target.version) { if (lookup.version.match(semver.semverRegEx)) target.setVersion('^' + lookup.version); else target.setVersion(lookup.version); } return Promise.resolve() .then(function() { // now check we are happy to override dep (primary) if (!oldDep) return; // fill in the oldDep endpoint if it matches our target for replacement prompts if (!oldDep.endpoint && !initialTarget.endpoint && oldDep.name == initialTarget.name) { var v = oldDep.version; oldDep = new Package(target.name); oldDep.setVersion(v); } if (oldDep.exactName == target.exactName) return; return options.force ? Promise.resolve(true) : ui.confirm('%' + name + '% installed as `' + oldDep.exactName + '`, are you sure you want to install this to `' + target.exactName + '`?', true) .then(function(confirm) { if (!confirm) throw 'Operation cancelled'; }) }) .then(function() { // check we are happy to override map (primary) if (!oldMap) return; if (oldMap.exactName == target.exactName) return; if (oldDep && oldMap.exactName == oldDep.exactName) return; return options.force ? Promise.resolve(true) : ui.confirm('%' + name + '% is configured to `' + oldMap.exactName + '`, are you sure you want to change this to `' + target.exactName + '`?', true) .then(function(confirm) { if (!confirm) throw 'Operation cancelled'; }); }) .then(function() { // if secondary, add the parent map if (options.primary) return; // add deps into our depMap, asking about changes where necessary var depMap = config.depMap[options.parent] = config.depMap[options.parent] || {}; if (!depMap[name] || depMap[name].exactName == target.exactName) { depMap[name] = target; return; } // overriding previous dependency - ask if (options.force) return; return ui.confirm('`' + options.parent + '` currently has dependency %' + name + '% set to `' + depMap[name].exactName + '`, but the upgrade expects `' + target.exactName + '`. Update?', true) .then(function(confirm) { if (confirm) depMap[name] = target; }); }) .then(function() { // add the version var versionList = config.versions[lookup.name] = config.versions[lookup.name] || []; if (versionList.indexOf(lookup.version) == -1) versionList.push(lookup.version); // only add as a base-level dependency name if primary if (options.primary) { config.dependencies[name] = target; config.baseMap[name] = target; } }) })
function loadExistingRange(name, parent, inject) { if (parent && secondaryRanges[parent] && secondaryRanges[parent][name]) return; else if (!parent && primaryRanges[name]) return; var _target; return Promise.resolve() .then(function() { if (!parent) return config.pjson.dependencies[name]; return Promise.resolve() .then(function() { if (secondaryDepsPromises[parent]) return secondaryDepsPromises[parent]; return Promise.resolve() .then(function() { var parentPkg = new PackageName(parent); var pjsonPath = path.resolve(parentPkg.getPath(), '.jspm.json'); // if the package is installed but not in jspm_packages // then we wait on the getPackageConfig or download of the package here return secondaryDepsPromises[parent] = new Promise(function(resolve, reject) { if (inject) return pkg.inject(parentPkg, resolve).catch(reject); fs.exists(pjsonPath, function(exists) { if (exists) return resolve(); pkg.download(parentPkg, null, resolve).catch(reject); }); }) .then(function(depMap) { if (depMap) return depMap; return readJSON(pjsonPath) .then(function(pjson) { return pkg.processDeps(pjson.dependencies || {}, pjson.registry); }); }); }); }) .then(function(deps) { return deps[name]; }); }) .then(function(target) { if (!target) { ui.log('warn', (parent ? '%' + parent + '% dependency %' : '%') + name + '% is installed in the config file, but is not a dependency in the package.json. It is advisable to add it to the package.json file.'); return; } _target = target.copy(); // locate the target return pkg.locate(_target) .then(function(located) { if (parent) { secondaryRanges[parent] = secondaryRanges[parent] || {}; secondaryRanges[parent][name] = located; } else { primaryRanges[name] = located; } }); }); }
var install = exports.install = function(name, target, options) { if (!name) return Promise.resolve(); var args = arguments; if (!config.loaded) return config.load().then(function() { return install.apply(this, args); }); // install('jquery') if (arguments.length == 1) { options = {}; target = ''; } // install(true, options) - from package.json if (name === true) { if (target === undefined && options === undefined) { options = {}; target = ''; } name = config.dependencies; } // install('jquery', options) if (!options && typeof target == 'object') { options = target; target = ''; } // install({ jquery: '1.5' }, options) if (typeof name == 'object') { var promises = []; for (var d in name) promises.push(install(d, name[d], options)); return Promise.all(promises); } // set default options if (!('primary' in options)) options.primary = true; if (!(target instanceof Package)) { // convert shortcut version-only form if (target.indexOf('@') == -1 && target.indexOf(':') == -1) target = name + '@' + (target == '*' || !target ? '' : target); target = new Package(target); } // our lookup match - general information // extra info - lookup.alreadyDownloading, lookup.fresh (added by download) var lookup; var initialTarget = target; // when installing over an existing dep, need to check against the old config // to be sure we're not overriding something important var oldDep, oldMap, oldVersions; return pkg.locate(target) // if not a primary install, and we have something that satisfies this already, then use that // otherwise do the full lookup .then(function(_target) { target = _target; if (options.primary) return; var versionList = config.versions[target.name]; if (!versionList) return; versionList.sort(semver.compare); // if not primary, and there is an existing compatible match, use it rather if (!options.force) for (var i = versionList.length - 1; i >= 0; i--) { var curVersion = versionList[i]; if (!semver.match(target.version, versionList[i])) continue; var _lookup = new Package(target.exactName); _lookup.setVersion(curVersion); return _lookup; } }) .then(function(_lookup) { return pkg.lookup(_lookup || target); }) .then(function(_lookup) { lookup = _lookup; if (!options.primary) return; // store these, as about to be removed oldDep = config.dependencies[name]; oldMap = config.baseMap[name]; oldVersions = oldMap && config.versions[oldMap.name]; // prune out the old name from the tree if there is one // acts only on config return removePackage(name); }) .then(function(deprecated) { // about to modify oldVersions potentially oldVersions = (oldVersions || []).concat([]); deprecated = deprecated || []; var versionList = config.versions[lookup.name] || []; // check to see if any old versions of this package can be replaced for all dependencies by this lookup version var useExisting = false; check: for (var i = 0; i < versionList.length; i++) { var curVersion = versionList[i]; // find the critical ranges this version is in (the ranges only it can support) var ranges = getCriticalRanges(target.name, curVersion); // if this version satisfies all of the ranges, then we can replace with this version for (var j = 0; j < ranges.length; j++) { if (!semver.match(ranges[j], lookup.version)) continue check; } // if the version is not equal to our target, deprecate the old version if (lookup.version != curVersion) { var oldName = lookup.name + '@' + curVersion; if (ranges.length) { useExisting = true; ui.log('info', (nodeSemver.gt(lookup.version, curVersion) ? 'Upgrading' : 'Downgrading') + ' `' + oldName + '` to `' + lookup.version + '`'); } else { // wasn't critical anyway - just remove deprecated.push(oldName); } // remove all traces, but leave the package in the file system for cache value delete config.depMap[oldName]; versionList.splice(i--, 1); } } // otherwise see if this target is supported by any of the existing dependencies // if so, change lookup to the existing dependency, and note if it is actually a change // this is the same check we did for secondary above, but we do it here after trying an upgrade for primary versions if (!useExisting) for (var i = versionList.length - 1; i >= 0; i--) { var curVersion = versionList[i]; if (target.version && !semver.match(target.version, curVersion)) continue; useExisting = true; if (lookup.version != curVersion) { ui.log('info', 'Using existing version `' + lookup.name + '@' + curVersion + '`, even though the latest is `' + lookup.version + '` as the tree can\'t be upgraded without forking'); lookup.setVersion(curVersion); } break; } // now log deprecations (as we're about to ask a question) for (var i = 0; i < deprecated.length; i++) { if (deprecated[i] != lookup.exactName) ui.log('info', 'Deprecating `' + deprecated[i] + '`'); } // we let this all the way down here as deprecation logging was only just above if (!versionList || !versionList.length) return; // if the fork version was actually already in our list of versions previously, then don't ask again if (oldVersions.indexOf(lookup.version) != -1) useExisting = true; // finally, we are now forking, so note the fork and ask for confirmation // disabled - fork prompts == annoying if (!useExisting) ui.log('info', '%Forking% `' + lookup.name + '` to use versions `' + versionList.concat([lookup.version]).join('`, `') + '`'); /* return options.force ? Promise.resolve(true) : ui.confirm('`' + lookup.name + '` already has version' + (versionList.length > 1 ? 's `' : ' `') + versionList.join('`, `') + '` installed, which can\'t upgrade to `' + lookup.version + '`. Are you sure you want to install a version fork?', true) .then(function(confirm) { if (!confirm) throw 'Operation cancelled'; }) */ }) // ensure we're happy overriding any map or dependencies // then write in our new config.baseMap and config.dependencies .then(function() { // set dependency version range to semver-compatible when none provided if (!target.version) { if (lookup.version.match(semver.semverRegEx)) target.setVersion('^' + lookup.version); else target.setVersion(lookup.version); } return Promise.resolve() .then(function() { // now check we are happy to override dep (primary) if (!oldDep) return; // fill in the oldDep endpoint if it matches our target for replacement prompts if (!oldDep.endpoint && !initialTarget.endpoint && oldDep.name == initialTarget.name) { var v = oldDep.version; oldDep = new Package(target.name); oldDep.setVersion(v); } if (oldDep.exactName == target.exactName) return; return options.force ? Promise.resolve(true) : ui.confirm('%' + name + '% installed as `' + oldDep.exactName + '`, are you sure you want to install this to `' + target.exactName + '`?', true) .then(function(confirm) { if (!confirm) throw 'Operation cancelled'; }) }) .then(function() { // check we are happy to override map (primary) if (!oldMap) return; if (oldMap.exactName == target.exactName) return; if (oldDep && oldMap.exactName == oldDep.exactName) return; return options.force ? Promise.resolve(true) : ui.confirm('%' + name + '% is configured to `' + oldMap.exactName + '`, are you sure you want to change this to `' + target.exactName + '`?', true) .then(function(confirm) { if (!confirm) throw 'Operation cancelled'; }); }) .then(function() { // if secondary, add the parent map if (options.primary) return; // add deps into our depMap, asking about changes where necessary var depMap = config.depMap[options.parent] = config.depMap[options.parent] || {}; if (!depMap[name] || depMap[name].exactName == target.exactName) { depMap[name] = target; return; } // overriding previous dependency - ask if (options.force) return; return ui.confirm('`' + options.parent + '` currently has dependency %' + name + '% set to `' + depMap[name].exactName + '`, but the upgrade expects `' + target.exactName + '`. Update?', true) .then(function(confirm) { if (confirm) depMap[name] = target; }); }) .then(function() { // add the version var versionList = config.versions[lookup.name] = config.versions[lookup.name] || []; if (versionList.indexOf(lookup.version) == -1) versionList.push(lookup.version); // only add as a base-level dependency name if primary if (options.primary) { config.dependencies[name] = target; config.baseMap[name] = target; } }) }) .then(function() { // before going ahead with install ensure we haven't already downloaded this already in this session // ideally we should wait for dep to complete, but circular dependencies break this if ((lookup.alreadyInstalling = installs.indexOf(lookup.exactName) != -1)) return; installs.push(lookup.exactName); if (options.inject) return pkg.inject(lookup, options.override); else return pkg.download(lookup, config.jspmPackages, options.override, options.force); }) .then(function(depMap) { // if we already have a depMap for this dependency, use that rather if (!options.force && depMap && config.depMap[lookup.exactName]) { // we copy any deps from depMap not in the existing dep map // main reason for this is to support "nodelibs", which is // a hidden dependency to avoid configuration clutter // there is probably a better way var curDepMap = {}; for (var d in config.depMap[lookup.exactName]) curDepMap[d] = config.depMap[lookup.exactName][d].exactName; for (var d in depMap) { if (!curDepMap[d]) curDepMap[d] = depMap[d]; } depMap = curDepMap; } if (!depMap || lookup.fresh) return; return install(depMap, { force: options.force, inject: options.inject, primary: false, parent: lookup.exactName }); }) // save the changes only for primary installs once we're sure the full tree has worked out .then(function() { if (!options.primary) return; return config.save(); }) .then(function() { if (lookup.alreadyInstalling) return; if (options.primary) ui.log('ok', (!lookup.fresh ? (options.inject ? 'Injected' : 'Installed') : 'Up to date -') + ' %' + name + '% as `' + target.exactName + '` (' + lookup.version + ')'); else ui.log('ok', (lookup.fresh ? 'Up to date - `' : '`') + target.exactName + '` (' + lookup.version + ')'); }); }
this.requestPinsAndHistory = function (tribeId) { return Promise.all([this.requestPins(tribeId), this.requestHistory(tribeId)]).then(function (arrayOfResults) { return {pins: arrayOfResults[0], history: arrayOfResults[1]}; }, handleMongoError); };
}).catch(function(err) { logger.warn('Failed updating marvin with new password for', user.username, 'error:', err.message); return rsvp.Promise.reject('Failed updating marvin with new password.'); });
export function promiseObject(promise, label) { return PromiseObject.create({ promise: Promise.resolve(promise, label), }); }
lookup: function() { return RSVP.Promise.reject("nodegit needs replaced"); }
export function promiseArray(promise, label) { return PromiseArray.create({ promise: Promise.resolve(promise, label), }); }
yield timeout(4000); this._transitionAfterSubmission(); }).drop(), _saveInvites(authorRole) { let users = this.get('validUsersArray'); return RSVP.Promise.all( users.map((user) => { let invite = this.store.createRecord('invite', { email: user, role: authorRole }); return invite.save().then(() => ({ email: user, success: invite.get('status') === 'sent' })).catch(error => ({ error, email: user, success: false })); }) ); }, _showNotifications(invites) { let notifications = this.get('notifications'); let erroredEmails = []; let successCount = 0; let invitationsString, message;
// Read the `tree` and return its node, which in particular contains the // tree's output directory (node.directory) function readAndReturnNodeFor (tree) { // To do: Complain about parallel execution // To do: Timing var index = newTreesRead.indexOf(tree) if (index !== -1) { // Return node from cache to deduplicate `.read` if (nodeCache[index].directory == null) { // node.directory gets set at the very end, so we have found an as-yet // incomplete node. This can happen if there is a cycle. throw new Error('Tree cycle detected') } return Promise.resolve(nodeCache[index]) } var node = { tree: tree, subtrees: [], selfTime: 0, totalTime: 0 } newTreesRead.push(tree) nodeCache.push(node) var treeDirPromise if (typeof tree === 'string') { treeDirPromise = Promise.resolve() .then(function () { if (willReadStringTree) willReadStringTree(tree) return tree }) } else if (!tree || typeof tree.read !== 'function') { throw new Error('Invalid tree found. You must supply a path or an object with a `read` function.'); } else { var now = process.hrtime() var totalStartTime = now var selfStartTime = now var readTreeRunning = false treeDirPromise = Promise.resolve() .then(function () { return tree.read(function readTree (subtree) { if (readTreeRunning) { throw new Error('Parallel readTree call detected; read trees in sequence, e.g. using https://github.com/joliss/promise-map-series') } readTreeRunning = true // Pause self timer var now = process.hrtime() node.selfTime += (now[0] - selfStartTime[0]) * 1e9 + (now[1] - selfStartTime[1]) selfStartTime = null return Promise.resolve() .then(function () { return readAndReturnNodeFor(subtree) // recurse }) .then(function (childNode) { node.subtrees.push(childNode) return childNode.directory }) .finally(function () { readTreeRunning = false // Resume self timer selfStartTime = process.hrtime() }) }) }) .then(function (dir) { if (readTreeRunning) { throw new Error('.read returned before readTree finished') } var now = process.hrtime() node.selfTime += (now[0] - selfStartTime[0]) * 1e9 + (now[1] - selfStartTime[1]) node.totalTime += (now[0] - totalStartTime[0]) * 1e9 + (now[1] - totalStartTime[1]) return dir }) } return treeDirPromise .then(function (treeDir) { if (treeDir == null) throw new Error(tree + ': .read must return a directory') node.directory = treeDir return node }) }
// error , function(err) { logger.error('error checking for JQuery on page ', state.pageUrl); return RSVP.Promise.reject(err); });
this.jobs.stats().then(function(data) { self.set('stats', data); return self.getCountBreakdowns(); }) .then(function(res) { self.set('breakdowns', res); self.get('indexController').set('breakdowns', res); }); }, getAllStates(type) { var promises = this.get('jobs.STATES').map((state) => { var query = { type: type, state: state }; return this.jobs.stats(query).then( res => _.extend(res, query) ); }); return Promise.all(promises); }, getCountBreakdowns() { return this.jobs.stats().then((stats) => { return this.indexController.set('stats', stats); }) .then(() => this.jobs.types()) .then((types) => { var promises = types.map(type => this.getAllStates(type)); return Promise.all(promises).then(_.flatten); }); }, actions: { goToTypeRoute(obj) {
function() { logger.info('script ' + JQUERY_SCRIPT_LOCATION + ' included on page' + state.pageUrl); return RSVP.Promise.resolve(); }
return Promise.all(load.deps.map(function(dep) { return Promise.resolve(visitTree(tree, load.depMap[dep], visit, seen)); })).then(function() {
// error , function(err) { logger.error('error including JQuery ', state.pageUrl); return RSVP.Promise.reject(err); });
}, async loadLocale(locale) { assert('locale is set', locale); if (this.exists('yes', locale)) { return; } let promises = [this._loadTranslation(locale)]; if (window.Intl === window.IntlPolyfill) { promises.push(this._loadPolyfillData(locale)); } await Promise.all(promises); }, async _loadTranslation(locale) { assert('locale is set', locale); debug(`Loading translations for locale: ${locale}`); let translations = await this.ajax.request(`/translations/${locale}.json`); await this.addTranslations(locale, translations); }, async _loadPolyfillData(locale) { assert('locale is set', locale); debug(`Loading polyfill data for locale: ${locale}`); await loadJS(`/assets/intl/locales/${locale}.js`); },
var readJobsInventories = new RSVP.Promise(function (resolve, reject){ var data = []; // Get all job files fs.readdir(folder, function(err, files){ // loop each files for (var afile of files){ // Check if files is Software jobs if (afile.search('Software_Jobs_By') !== -1) { // Get date from filename var result = afile.match(/_(\d\d)(\d\d)(\d\d)_/); //var date = result[2] +'/' + convertInt(result[3] - 1) + '/20' + result[1]; var date = result[2] +'/' + convertInt(result[3]) + '/20' + result[1]; log("Read file "+ afile + " for date: "+ date); // handler of line reader var lineReader = require('readline').createInterface({ input: fs.createReadStream(folder+'/' + afile) }); // Line read Event lineReader.on('line', function (line) { if (line.search(date) != -1){ info('date found: ' + date); var items = line.split(','); var elems = items[0].split('.'); var time = items[7].split(' '); data.push({'filename':afile, 'string':elems[1], 'server':elems[0], 'package':items[2], 'version':items[3], 'procedure':items[4], 'status':items[5], 'tack':items[6], 'date':time[0], 'time':time[1] }); } }); // Close Event lineReader.on('close', function(){ log("List data provide to database"); log(data); resolve(data); }); } } }); });
.then(function(fresh) { pkg.fresh = fresh; if (fresh) return false; cli.log('info', 'Downloading `' + pkg.exactName + '`'); return Promise.all([ override ? Promise.resolve(override) : _pkg.checkOverride(pkg.exactName, true), Promise.resolve(downloadDir) // ensure the download directory exists .then(asp(mkdirp)) // clear the directory .then(function() { return asp(rimraf)(downloadDir); }) .then(function() { return asp(fs.mkdir)(downloadDir) }) // do the download .then(function() { return new Promise(function(resolve, reject) { var exactVersion = versionCache[pkg.package][pkg.version].original || pkg.version; var promise = _pkg.loadEndpoint(pkg.endpoint).download(pkg.package, exactVersion, pkg.hash, downloadDir, resolve, reject); if (promise) promise.then(resolve, reject); }); }) // if the download defines the package.json use that // otherwise load the package.json .then(function(pjson) { if (pjson) return pjson; return asp(fs.readFile)(path.resolve(downloadDir, 'package.json')) .then(function(data) { try { return JSON.parse(data); } catch(e) {} }, function() {}); }) ]) // apply the overrides to get a final package.json .then(function(pjsons) { var pjson = pjsons && pjsons[1] || {}; var override = pjsons && pjsons[0]; // apply the jspm internal overrides first if (pjson.jspm) extend(pjson, pjson.jspm); if (override && override.jspm) extend(override, override.jspm); if (override) extend(pjson, override); if (typeof pjson.registry == 'string' && pjson.registry.toLowerCase == 'npm') pjson.useJSExtensions = true; // parse the dependencies pjson.dependencies = config.parseDependencies(pjson.dependencies, pjson.registry); // having parsed, note now that we are in the jspm registry form pjson.registry = 'jspm'; // if there is a "browser" object, convert it into map config for browserify support if (typeof pjson.browser == 'object') { pjson.map = pjson.map || {}; for (var b in pjson.browser) { var mapping = pjson.browser[b]; if (b.substr(b.length - 3, 3) == '.js') b = b.substr(0, b.length - 3); if (mapping.substr(mapping.length - 3, 3) == '.js') mapping = mapping.substr(0, mapping.length - 3); // local maps not supported since this affects the external // interface for all other modules // only way to implement is through a module alias replacement // may be worth considering at some point if (b.substr(0, 2) == './') continue; pjson.map[b] = pjson.map[b] || mapping; } } return pjson; }) // apply build operations from the package.json .then(function(pjson) { // don't build in dependencies var pjsonObj = extend({}, pjson); delete pjsonObj.dependencies; return build.buildPackage(downloadDir, pjsonObj, path.relative(process.cwd(), downloadDir)) .then(function() { return pjson; }); }) // save the final calculated package.json in place .then(function(pjson) { return asp(fs.writeFile)(path.resolve(downloadDir, 'package.json'), JSON.stringify(pjson, null, 2)) .then(function() { return pjson; }); }) // create the main entry point .then(function(pjson) { var lastNamePart = pkg.name.split('/').pop().split(':').pop(); var main = typeof pjson.browser == 'string' && pjson.browser || typeof pjson.main == 'string' && pjson.main; var hasMain = !!main; if (main) { if (main.substr(0, 2) == './') main = main.substr(2); if (main.substr(main.length - 3, 3) == '.js') main = main.substr(0, main.length - 3); } main = main || 'index' || lastNamePart; // try the package.json main return new Promise(function(resolve, reject) { fs.exists(path.resolve(downloadDir, main.substr(main.length - 3, 3) != '.js' ? main + '.js' : main), resolve); }) .then(function(exists) { if (!exists && hasMain) return cli.log('warn', 'No main entry point found for `' + pkg.exactName + '`'); // create the main pointer var mainFile = path.resolve(downloadDir, '../' + lastNamePart + '@' + pkg.version + '.js'); return asp(fs.writeFile)(mainFile, 'export * from "' + pkg.exactName + '/' + main + '";'); }) .then(function() { // finally add the .jspm-hash return asp(fs.writeFile)(path.resolve(downloadDir, '.jspm-hash'), pkg.hash) }) .then(function() { return pjson; }) }) })
.then(function(source) { source += ''; return Promise.resolve() // add shim config if necessary .then(function() { if (!options.shim) return; var match; if (!(match = matchWithWildcard(options.shim, relModule))) return; var curShim = options.shim[match]; if (curShim instanceof Array) curShim = { deps: curShim }; // NB backwards-compatible with shim.imports curShim.deps = curShim.deps || curShim.imports; if (typeof curShim.deps === 'string') curShim.deps = [curShim.deps]; var depStr = '"format global";' + nl; if (curShim.deps) for (var i = 0; i < curShim.deps.length; i++) depStr += '"deps ' + curShim.deps[i] + '";' + nl; if (curShim.exports) depStr += '"exports ' + curShim.exports + '";' + nl; changed = true; source = depStr + source; return true; }) // add any format hint if provided // only add format hint if detection would fail // also set the format here if not set // NB all regexs should apply after removing comments // also ideally format injection should be post-minification // in case of minification quirks .then(function(shimmed) { // don't add format if already shimmed! if (shimmed) return; var detected = detectFormat(source); // don't rewrite meta if (detected.meta) { format = detected.format; return; } if (options.alwaysIncludeFormat || !format || detected.format !== format) { changed = true; source = '"format ' + (format || detected.format) + '";' + nl + source; } if (!format) format = detected.format; }) // apply map config .then(function() { // ES6 if (format === 'es6') { source = source.replace(es6DepRegEx, function(statement, start, type, str, singleString, doubleString) { var name = singleString || doubleString; var mapped = applyMap(name, map, relFile, options.removeJSExtensions); if (!mapped) return statement; changed = true; return statement.replace(new RegExp('"' + name + '"|\'' + name + '\'', 'g'), '\'' + mapped + '\''); }); } // AMD else if (format === 'amd') { amdDefineRegEx.lastIndex = 0; var defineStatement = amdDefineRegEx.exec(source); if (defineStatement) { if (!defineStatement[2]) return; var depArray = eval(defineStatement[2]); depArray = depArray.map(function(name) { var mapped = applyMap(name, map, relFile, options.removeJSExtensions); if (!mapped) return name; changed = true; return mapped; }); if (changed) source = source.replace(defineStatement[2], JSON.stringify(depArray)); } } // CommonJS else if (format === 'cjs') { source = source.replace(cjsRequireRegEx, function(statement, singleString, doubleString) { var name = singleString || doubleString; name = name.substr(1, name.length - 2); var mapped = applyMap(name, map, relFile, options.removeJSExtensions); if (!mapped) return statement; changed = true; return statement.replace(new RegExp('"' + name + '"|\'' + name + '\'', 'g'), '\'' + mapped + '\''); }); } // Global? (including shim?) // else { // } }) // if changed, save these meta-updates into the original file .then(function() { // ensure there is a comment at the beginning of the file // this is necessary to protect the source map when wrapping if (!source.match(initialCommentRegEx)) { source = '\/* *\/ \n' + source; changed = true; } if (changed) return asp(fs.writeFile)(file, source); }) // transpile .then(function() { if (!options.transpile) return; var traceur = require('traceur'); traceur.options.sourceMaps = true; traceur.options.modules = 'instantiate'; try { var compiler = new traceur.Compiler({ moduleName: '', modules: 'instantiate' }); source = compiler.compile(source, relFile, path.basename(relFile.replace(/\.js$/, '.src.js'))); sourceMap = compiler.getSourceMap(); } catch(e) { // an error in one compiled file doesn't stop all compilation if (!e.stack) compileErrors += + '\n'; else compileErrors += e.stack + '\n' + relFile + ': Unable to transpile ES6\n'; } }) // minify .then(function() { if (!options.minify) return; var uglify = require('uglify-js'); try { var ast = uglify.parse(source, { filename: path.basename(relFile.replace(/\.js$/, '.src.js')) }); ast.figure_out_scope(); ast = ast.transform(uglify.Compressor({ warnings: false, evaluate: false })); ast.figure_out_scope(); ast.compute_char_frequency(); ast.mangle_names({ except: ['require'] }); var source_map = uglify.SourceMap({ file: path.basename(relFile), orig: sourceMap }); source = ast.print_to_string({ ascii_only: true, // for some reason non-ascii broke esprima comments: function(node, comment) { return comment.line === 1 && comment.col === 0; }, source_map: source_map }); sourceMap = source_map.toString(); } catch(e) { // an error in one compiled file doesn't stop all compilation compileErrors += relFile + ': Unable to minify file\n'; } }) // finally, if compiled, rename to the new file with source maps .then(function() { if (!options.minify && !options.transpile) return; // rename the original with meta changes to .src.js return asp(fs.rename)(file, file.replace(/\.js$/, '.src.js')) // write .js as the current source, with a source map comment .then(function() { return asp(fs.writeFile)(file, source + '\n//# sourceMappingURL=' + relFile.split('/').pop() + '.map'); }) // write the source map to .js.map .then(function() { return asp(fs.writeFile)(file + '.map', sourceMap); }); }); }, function(e) {
/** A Transition is a thennable (a promise-like object) that represents an attempt to transition to another route. It can be aborted, either explicitly via `abort` or by attempting another transition while a previous one is still underway. An aborted transition can also be `retry()`d later. @class Transition @constructor @param {Object} router @param {Object} intent @param {Object} state @param {Object} error @private */ function Transition(router, intent, state, error, previousTransition) { var transition = this; this.state = state || router.state; this.intent = intent; this.router = router; this.data = this.intent && this.intent.data || {}; this.resolvedModels = {}; this.queryParams = {}; this.promise = undefined; this.error = undefined; this.params = undefined; this.handlerInfos = undefined; this.targetName = undefined; this.pivotHandler = undefined; this.sequence = undefined; this.isAborted = false; this.isActive = true; if (error) { this.promise = Promise.reject(error); this.error = error; return; } // if you're doing multiple redirects, need the new transition to know if it // is actually part of the first transition or not. Any further redirects // in the initial transition also need to know if they are part of the // initial transition this.isCausedByAbortingTransition = !!previousTransition; this.isCausedByInitialTransition = ( previousTransition && ( previousTransition.isCausedByInitialTransition || previousTransition.sequence === 0 ) ); if (state) { this.params = state.params; this.queryParams = state.queryParams; this.handlerInfos = state.handlerInfos; var len = state.handlerInfos.length; if (len) { this.targetName = state.handlerInfos[len-1].name; } for (var i = 0; i < len; ++i) { var handlerInfo = state.handlerInfos[i]; // TODO: this all seems hacky if (!handlerInfo.isResolved) { break; } this.pivotHandler = handlerInfo.handler; } this.sequence = router.currentSequence++; this.promise = state.resolve(checkForAbort, this)['catch']( catchHandlerForTransition(transition), promiseLabel('Handle Abort')); } else { this.promise = Promise.resolve(this.state); this.params = {}; } function checkForAbort() { if (transition.isAborted) { return Promise.reject(undefined, promiseLabel("Transition aborted - reject")); } } }
var RSVP = require("rsvp"); function dieToss() { return Math.floor(Math.random() * 6) + 1; } console.log('1'); var promise = new RSVP.Promise(function(fulfill, reject) { var n = dieToss(); if (n === 6) { fulfill(n); } else { reject(n); } console.log('2'); }); promise.then(function(toss) { console.log ('Yay, thew a ' + toss + '.'); }, function(toss) { console.log('Oh noes, threw a ' + toss + '.'); }); console.log('3');