.then(function() { if (cname) { // ok or manual return Promise.cast(City.findOne({'zs': zs, 'cities.cn': cname}, {sid: 1, sn: 1, zn: 1, zid: 1, 'cities.$': 1}).exec()) .then(function(d) { if (!d) { return Promise.resolve() } else { var zn = d.zn var sn = d.sn || '' var cn = d.cities ? d.cities[0].cn : '' var zid = d.zid var sid = d.sid || -1 var cid = (d.cities ? d.cities[0].cid : -1) return that.__insertAndUpdateWithIds(zn, sn, cn, zid, sid, cid, lon, lat, status) } }) } else { // ok or manual return Promise.cast(City.findOne({'zs': zs}, {sid: 1, sn: 1, zn: 1, zid: 1}).exec()) .then(function(d) { if (!d) { return Promise.resolve() } else { var zn = d.zn var sn = d.sn || '' var cn = '' var zid = d.zid var sid = d.sid || -1 var cid = (d.cities ? d.cities[0].cid : -1) return that.__insertAndUpdateWithIds(zn, sn, cn, zid, sid, cid, lon, lat, status) } }) } })
.then(function(d) { if (d) { return Promise.cast(that.update({lon: largeLon, lat: largeLat}, set).exec()) } else { return Promise.cast(that.create(set)) } }).then(function() {
exports.index = function (req, res) { var handler = req.handler, dataPromise = Promise.cast(null), htmlPromise = Promise.cast(null); if (handler) { // Cast to promise in case a non-promise is returned dataPromise = Promise.cast( handler.func(true)(req, res) ); var htmlPath = '/html/' + handler.resources.join('/') + '/' + handler.funcName + '.html'; htmlPromise = readHTML( path.join(process.cwd(), 'front', htmlPath) ); } Promise.props({ data: dataPromise, html: htmlPromise }) .then(function (preload) { var renderData = { appName: req.appName || 'Synth App', jsFiles: assets.jsFiles, cssFiles: assets.cssFiles, data: prepareData(preload.data), preloadHTML: preload.html, preloadHTMLPath: htmlPath }; for (var key in res.renderData) { renderData[key] = res.renderData[key]; } res.render( 'index', renderData); }); };
.then(function(d){ if (!d) { return Promise.cast(that.update({shop_id : shopId, stat_id: statId}, {$push : {votes : {user_id : userId, vote: vote}}}).exec()) .then(function(){return [-1, vote]; }); } else { return Promise.cast(that.update({shop_id : shopId, stat_id: statId, 'votes.user_id' : userId}, {'votes.$.vote' : vote}).exec()) .then(function(){return [d.votes[0].vote, vote]; }); } });
exports.index = function (req, res) { var handler = req.handler, dataPromise = Promise.cast(null), htmlPromise = Promise.cast(null); var preloadDataPath; if (handler) { // Cast to promise in case a non-promise is returned dataPromise = handler.func(true)(req, res); var htmlPath = '/html/' + handler.resources.join('/') + '/' + handler.funcName + '.html'; htmlPromise = readHTML( path.join(process.cwd(), 'front', htmlPath) ); preloadDataPath = handler.path; } Promise.props({ data: dataPromise, html: htmlPromise }) .then(function (preload) { var apiPrefetchData = {}; if (preload.data) { apiPrefetchData[preloadDataPath] = sanitizeData(preload.data); } if (preload.html) { apiPrefetchData[htmlPath] = preload.html.toString(); } var renderData = { appName: req.appName || 'Synth App', appVersion: req.appVersion, jsFiles: assets.jsFiles, cssFiles: assets.cssFiles, apiPrefetchData: JSON.stringify(apiPrefetchData) }; for (var key in res.renderData) { renderData[key] = res.renderData[key]; } res.render('index', renderData, function (err, html) { if (err) throw err; res.send(html); }); }) .catch(function (err) { console.error(err.toString()); if (process.env.NODE_ENV == 'production') { res.status(500).send("The server has encountered an error."); } else { res.status(500).send('<pre>' + err.toString() + '</pre>'); } }); };
function reduceStreamFn(el, enc) { var initial = this._initial, acc = this._acc; if (acc === null) acc = typeof(initial) !== 'undefined' ? Promise.cast(initial) : Promise.cast(el); else acc = Promise.join(acc, el, enc).spread(this._reducefn); this._acc = acc; return this.push(acc); }
listTweets: function(params) { var opts = { skip: _.parseInt( params.skip ) || 0, limit: _.parseInt( params.limit ) || app.config.feed.pagesize, sort: { id: -1 } }; var query = { hidden: { $exists: false } }; if(params.before && Date.parse( params.before )) { _.assign(query, { timestamp: { $lt: new Date( params.before ) } }); } if(params.after && Date.parse( params.after )) { _.assign(query, { timestamp: { $gt: new Date( params.after ) } }); } if(params.since && !_.isNaN( parseInt( params.since ) )) { _.assign(query, { id: { $gt: params.since } }); } if(params.priorTo && !_.isNaN( parseInt( params.priorTo ) )) { _.assign(query, { id: { $lt: params.priorTo } }); } var result = this.tweets.find( query, opts ) .error(function(err) { console.log( '## Data error: ', err ); }); return Promise.cast( result ); },
save: function() { var originalArguments = arguments; var beforeFn, afterFn; if (this.isNew()) { beforeFn = this.beforeCreate; afterFn = this.afterCreate; } else { beforeFn = this.beforeUpdate; afterFn = this.afterUpdate; } return Promise.cast().bind(this).then(function() { return beforeFn.apply(this, originalArguments); }).then(function() { return this.beforeSave.apply(this, originalArguments); }).then(function() { var op = Backbone.Model.prototype.save.apply(this, originalArguments); if (!op) { return Promise.reject(this.validationError); } return op; }).then(function() { return afterFn.apply(this, originalArguments); }).then(function() { return this.afterSave.apply(this, originalArguments); }); },
return new Promise(function (resolve) { var folder = getProjectRoot(); // if we previously tried, assume nothing has changed if (writeTestResults[folder]) { return resolve(writeTestResults[folder]); } // create entry for temporary file var fileEntry = FileSystem.getFileForPath(folder + ".bracketsGitTemp"); function finish(bool) { // delete the temp file and resolve fileEntry.unlink(function () { writeTestResults[folder] = bool; resolve(bool); }); } // try writing some text into the temp file Promise.cast(FileUtils.writeText(fileEntry, "")) .then(function () { finish(true); }) .catch(function () { finish(false); }); });
.then(function(d){ if (!d) { return Promise.cast(that.create({shop_id: shopId, stat_id : statId})); } else { return Promise.resolve(d); } });
.then(function(d) { if (!d) { return Promise.cast(that.create({lon: largeLon, lat: largeLat})) } else { return d } })
.then(function(d){ var blogger = d && d.bloggers && d.bloggers[0] || {}; shop.message = blogger.message; shop.blogger_name = blogger.blogger_name; shop.blogger_id = blogger.blogger_id; return Promise.cast(that.findOne({"shops.shop_id": shopId}).exec()); }).then(function(d){
function lintFile(filename) { var fullPath = Utils.getProjectRoot() + filename; return Promise.cast(CodeInspection.inspectFile(FileSystem.getFileForPath(fullPath))) .catch(function (err) { ErrorHandler.logError(err + " on CodeInspection.inspectFile for " + fullPath); }); }
.then(function(d){ if (!d) { // insert return Promise.cast(that.create({zid: zid, sid: sid, cid: cid, shops: []})); } else { // update return true; } })
FeaturedshopSchema.statics.insert = function(shop, user){ var shopId = shop && shop._id && shop._id.toString(); var userId = user && user._id && user._id.toString(); if (!mongoose.Types.ObjectId.isValid(shopId)) return res.json(500, {error: "text-error-shop-id"}); if (!mongoose.Types.ObjectId.isValid(userId)) return res.json(500, {error: "text-error-shop-id"}); var zid = shop.zid; var sid = shop.sid; var cid = shop.cid; var that = this; var ShopBlog = mongoose.model("ShopBlog"); return Promise.cast(ShopBlog.findOne({"shop_id": shopId}).exec()) .then(function(d){ var blogger = d && d.bloggers && d.bloggers[0] || {}; shop.message = blogger.message; shop.blogger_name = blogger.blogger_name; shop.blogger_id = blogger.blogger_id; return Promise.cast(that.findOne({"shops.shop_id": shopId}).exec()); }).then(function(d){ if (!d) { // insert return that._insert(shop, user) .then(function(){ return Promise.cast(that.update({zid:zid, sid:sid, cid:cid, "shops.shop_id" : {$nin : [shopId]}}, {$push : {"shops":shop}}).exec()); }); } else { // update return Promise.cast(that.update({zid:zid, sid:sid, cid:cid, "shops.shop_id":shopId }, {$set: {"shops.$": shop}}).exec()); } }); };
// Source: https://github.com/petkaantonov/bluebird/issues/70 // Waterfall function waterfall(tasks) { var current = Promise.cast(); for (var k = 0; k < tasks.length; ++k) { current = current.then(tasks[k]); } return current; }
// Sequence without waterfalling, returning all results: function multipleResultsDependentWaterfall(tasks) { var current = Promise.cast(), results = []; for (var k = 0; k < tasks.length; ++k) { results.push(current = current.thenReturn().then(tasks[k])); } return Promise.all(results); }
it('shouldn\'t enforce if we provide autoMigrateOldSchema option', function () { return Bluebird.cast().bind(this) .then(function () { return this.sequelize.getQueryInterface().describeTable('SequelizeMeta'); }) .then(function (fields) { expect(Object.keys(fields)).to.eql(['id', 'from', 'to']); }) .then(function () { return new Bluebird(function (fulfill, reject) { gulp .src(Support.resolveSupportPath('tmp')) .pipe(helpers.runCli('db:migrate', { pipeStderr: true })) .pipe(helpers.teardown(function (err, stderr) { if ( err || stderr ) { reject( err || stderr ); return; } fulfill(); })); }); }) .then(function () { return this.sequelize.getQueryInterface().describeTable('SequelizeMeta'); }) .then(function (fields) { expect(Object.keys(fields)).to.eql(['name']); }); });
SequelizeAdaptor.prototype._count = function(query) { var findOpts = {}; if (query) { findOpts.where = this._getQuery(query); } return Promise.cast(this.Model.count(findOpts)); };
run() { if (this.errorVal) { return Bluebird.reject(this.errorVal); } else { return Bluebird.cast(this.responseVal); } }
qall.filter = function (arr, fn) { if (!arr) { return Promise.reject(new TypeError('Must have array')) } if (typeof fn !== 'function') { return Promise.reject(new TypeError('fn must be a Function')) } return Promise.cast(arr).then(function (arr) { if (!Array.isArray(arr)) { throw new TypeError('arr must be an Array') } return new Promise(function (r, t) { qall.map(arr, fn) .then(function (keep) { r(arr.filter(function (el, i) { return keep[i] })) }, t) }) }) }
.then(function (issue) { var issueid = issue.id; var maxNumPic = 3; var p = Promise.cast(); var keyList = new Array(); for (var i = 0; i < maxNumPic; i++) { keyList.push('picture' + (i + 1)); } if (req.files) { _.every(keyList, function (v, i) { var key = v; if (req.files[key]) { p = p.then(function () { return Picture.forge({ issueid: issueid }).save() .then(function (picture) { return picture.updatePicture('avatar', req.files[key]['path']); }); }); return true; } }); } return p.then(function () { next({ msg: 'Issue posted', id: issueid }); }) }).catch(next);
AchievementSchema.statics.delete = function(id) { if (!mongoose.Types.ObjectId.isValid(id)) { return Promise.reject("not a valid achievement id"); } return Promise.cast(this.remove({_id: id}).exec()); };
it("are sent for multiple tickets", function() { var self = this; return Promise.cast([ self.ticket, self.otherTicket, self.yetAnother ]) .map(function(ticket) { return ticket.addFollower(self.user, self.user) .then(function() { return ticket.markAsRead(self.user); }).return(ticket); }) .delay(100) .map(function(ticket) { return ticket.addComment("a comment for every ticket", self.otherUser); }) .then(function() { return Ticket.collection().withUnreadComments(self.user).fetch(); }) .then(function(coll) { assert.equal(3, coll.size()); }); });
.then(function(patches){ if (!patches.length) return console.log('Component '+component+' is up to date.'); endVersion = patches[patches.length-1].num; console.log('Component '+component+' must be upgraded from version '+startVersion+' to '+endVersion); return Promise.cast(patches).bind(this) .then(proto.begin) .reduce(function(_, patch){ console.log('Applying patch '+patch.num+' : '+patch.name); return Promise.cast(patchDirectory+'/'+patch.filename).bind(this) .then(fs.readFileAsync.bind(fs)) .then(buffer => buffer.toString() .replace(/(#[^\n]*)?\n/g, ' ').split(';') .map(s => s.trim()).filter(Boolean) ).map(function(statement){ console.log(' Next statement :', statement); return this.execute(statement) }); }, 'see https://github.com/petkaantonov/bluebird/issues/70') .then(function(){ return this.execute("delete from db_version where component=$1", [component]) }) .then(function(){ return this.execute("insert into db_version (component,version) values($1,$2)", [component, endVersion]) }) .then(proto.commit) .then(function(){ console.log('Component '+component+' successfully upgraded to version '+endVersion) }) .catch(function(err){ console.log('An error prevented DB upgrade : ', err); console.log('All changes are rollbacked'); return this.rollback(); }); })
Manager.prototype.setBelongsToMany = function(model, key, models, relation) { var existing = model.related(key); return Promise.cast(existing.length ? existing : existing.fetch()).then(function() { return this.setCollection(existing, models); }.bind(this)).then(function(targets) { // Enforce attach/detach IDs existing.relatedData.parentId = model.id; existing.relatedData.parentFk = model.id; return targets.mapThen(function(target) { if (!existing.findWhere({ id: target.id })) { return existing.attach(target); } }).then(function() { return existing.mapThen(function(target) { if (!targets.findWhere({ id: target.id })) { return existing.detach(target); } }); }); }).then(function() { return model; }); };
getArtists: function(rootIds, artists, recurse){ var agg = [] , opts = { query: qHelpers.matchRoots(rootIds, recurse) || {} }; if ( artists ) _.extend(opts.query, { artist: qHelpers.matchArray(artists) }) opts.map = function(){ var id = this._id.str , image = this.image ? "/media/" + id + "/coverart" : '' , album = this.album ? this.album : ''; if ( this.artist ) this.artist.forEach(function(artist){ emit(artist, { _id: artist, albums: [ album ], images: [ image ]}) }) }; opts.reduce = function(key, values){ var rslt = { _id: key, albums: [], images: [] }; values.forEach(function(v, k){ if ( !~rslt.albums.indexOf(v.albums[0]) ){ rslt.albums.push(v.albums[0]); rslt.images.push(v.images[0]); } }) return rslt; } return Q.cast(Media.mapReduce(opts).then(function(data){ return _.pluck(data, 'value') })); },
.then(function (text) { if (text === null) { return resolve(); } if (removeBom) { // remove BOM - \uFEFF text = text.replace(/\uFEFF/g, ""); } if (normalizeLineEndings) { // normalizes line endings text = text.replace(/\r\n/g, "\n"); } // process lines var lines = text.split("\n"); if (lineNumbers) { lineNumbers.forEach(function (lineNumber) { if (typeof lines[lineNumber] === "string") { lines[lineNumber] = lines[lineNumber].replace(/\s+$/, ""); } }); } else { lines.forEach(function (ln, lineNumber) { if (typeof lines[lineNumber] === "string") { lines[lineNumber] = lines[lineNumber].replace(/\s+$/, ""); } }); } // add empty line to the end, i've heard that git likes that for some reason if (addEndlineToTheEndOfFile) { var lastLineNumber = lines.length - 1; if (lines[lastLineNumber].length > 0) { lines[lastLineNumber] = lines[lastLineNumber].replace(/\s+$/, ""); } if (lines[lastLineNumber].length > 0) { lines.push(""); } } text = lines.join("\n"); return Promise.cast(FileUtils.writeText(fileEntry, text)) .catch(function (err) { ErrorHandler.logError("Wasn't able to clean whitespace from file: " + fullPath); resolve(); throw err; }) .then(function () { // refresh the file if it's open in the background DocumentManager.getAllOpenDocuments().forEach(function (doc) { if (doc.file.fullPath === fullPath) { reloadDoc(doc); } }); // diffs were cleaned in this file resolve(); }); });
it('returns a promise resolving to its input', function(done) { Promise.cast(5) .then(tee(function() {})) .done(function(result) { expect(result).to.equal(5); done(); }); });
it('returns a promise that is rejected when the tee fails', function(done) { Promise.cast(5) .then(tee(function() {throw new Error('Fail');})) .done(null, function(reason) { expect(reason).to.be.an(Error); done(); }); });