不要怂,就是干,撸起袖子干!

You need to sign in or sign up before continuing.
Commit cf0e4626 by Andy Edwards Committed by GitHub

refactor: remove bluebird Promise.map and chained .map usage (#12064)

1 parent 45570b28
......@@ -37,10 +37,10 @@ function removeColumn(qi, tableName, columnName, options) {
// No foreign key constraints found, so we can remove the column
return;
}
return Promise.map(results, constraint => qi.sequelize.query(
return Promise.all(results.map(constraint => qi.sequelize.query(
qi.QueryGenerator.dropForeignKeyQuery(tableName, constraint.constraint_name),
Object.assign({ raw: true }, options)
));
)));
})
.then(() => qi.sequelize.query(
qi.QueryGenerator.removeColumnQuery(tableName, columnName),
......
......@@ -279,7 +279,7 @@ class Query extends AbstractQuery {
if (!tableNames.length) {
return executeSql();
}
return Promise.map(tableNames, tableName =>
return Promise.all(tableNames.map(tableName =>
new Promise(resolve => {
tableName = tableName.replace(/`/g, '');
columnTypes[tableName] = {};
......@@ -292,8 +292,7 @@ class Query extends AbstractQuery {
}
resolve();
});
})
).then(executeSql);
}))).then(executeSql);
}
return executeSql();
});
......@@ -425,7 +424,7 @@ class Query extends AbstractQuery {
handleShowIndexesQuery(data) {
// Sqlite returns indexes so the one that was defined last is returned first. Lets reverse that!
return Promise.map(data.reverse(), item => {
return Promise.all(data.reverse().map(item => {
item.fields = [];
item.primary = false;
item.unique = !!item.unique;
......@@ -441,7 +440,7 @@ class Query extends AbstractQuery {
return item;
});
});
}));
}
getDatabaseMethod() {
......
......@@ -1818,7 +1818,7 @@ class Model {
if (!results.length) return original;
return Promise.map(options.include, include => {
return Promise.all(options.include.map(include => {
if (!include.separate) {
return Model._findSeparate(
results.reduce((memo, result) => {
......@@ -1856,7 +1856,7 @@ class Model {
);
}
});
}).return(original);
})).return(original);
}
/**
......@@ -2607,11 +2607,10 @@ class Model {
const validateOptions = _.clone(options);
validateOptions.hooks = options.individualHooks;
return Promise.map(instances, instance =>
return Promise.all(instances.map(instance =>
instance.validate(validateOptions).catch(err => {
errors.push(new sequelizeErrors.BulkRecordError(err, instance));
})
).then(() => {
}))).then(() => {
delete options.skip;
if (errors.length) {
throw errors;
......@@ -2621,7 +2620,7 @@ class Model {
}).then(() => {
if (options.individualHooks) {
// Create each instance individually
return Promise.map(instances, instance => {
return Promise.all(instances.map(instance => {
const individualOptions = _.clone(options);
delete individualOptions.fields;
delete individualOptions.individualHooks;
......@@ -2630,14 +2629,14 @@ class Model {
individualOptions.hooks = true;
return instance.save(individualOptions);
});
}));
}
return Promise.resolve().then(() => {
if (!options.include || !options.include.length) return;
// Nested creation for BelongsTo relations
return Promise.map(options.include.filter(include => include.association instanceof BelongsTo), include => {
return Promise.all(options.include.filter(include => include.association instanceof BelongsTo).map(include => {
const associationInstances = [];
const associationInstanceIndexToInstanceMap = [];
......@@ -2668,7 +2667,7 @@ class Model {
instance[include.association.accessors.set](associationInstance, { save: false, logging: options.logging });
}
});
});
}));
}).then(() => {
// Create all in one query
// Recreate records from instances to represent any changes made in hooks or validation
......@@ -2748,8 +2747,8 @@ class Model {
if (!options.include || !options.include.length) return;
// Nested creation for HasOne/HasMany/BelongsToMany relations
return Promise.map(options.include.filter(include => !(include.association instanceof BelongsTo ||
include.parent && include.parent.association instanceof BelongsToMany)), include => {
return Promise.all(options.include.filter(include => !(include.association instanceof BelongsTo ||
include.parent && include.parent.association instanceof BelongsToMany)).map(include => {
const associationInstances = [];
const associationInstanceIndexToInstanceMap = [];
......@@ -2821,7 +2820,7 @@ class Model {
return recursiveBulkCreate(throughInstances, throughOptions);
}
});
});
}));
}).then(() => {
// map fields back to attributes
instances.forEach(instance => {
......@@ -2925,8 +2924,7 @@ class Model {
}).then(() => {
// Get daos and run beforeDestroy hook on each record individually
if (options.individualHooks) {
return this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark })
.map(instance => this.runHooks('beforeDestroy', instance, options).then(() => instance))
return this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark }).then(value => Promise.all(value.map(instance => this.runHooks('beforeDestroy', instance, options).then(() => instance))))
.then(_instances => {
instances = _instances;
});
......@@ -2952,7 +2950,7 @@ class Model {
}).tap(() => {
// Run afterDestroy hook on each record individually
if (options.individualHooks) {
return Promise.map(instances, instance => this.runHooks('afterDestroy', instance, options));
return Promise.all(instances.map(instance => this.runHooks('afterDestroy', instance, options)));
}
}).tap(() => {
// Run after hook
......@@ -2999,8 +2997,7 @@ class Model {
}).then(() => {
// Get daos and run beforeRestore hook on each record individually
if (options.individualHooks) {
return this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark, paranoid: false })
.map(instance => this.runHooks('beforeRestore', instance, options).then(() => instance))
return this.findAll({ where: options.where, transaction: options.transaction, logging: options.logging, benchmark: options.benchmark, paranoid: false }).then(value => Promise.all(value.map(instance => this.runHooks('beforeRestore', instance, options).then(() => instance))))
.then(_instances => {
instances = _instances;
});
......@@ -3018,7 +3015,7 @@ class Model {
}).tap(() => {
// Run afterDestroy hook on each record individually
if (options.individualHooks) {
return Promise.map(instances, instance => this.runHooks('afterRestore', instance, options));
return Promise.all(instances.map(instance => this.runHooks('afterRestore', instance, options)));
}
}).tap(() => {
// Run after hook
......@@ -3148,7 +3145,7 @@ class Model {
let changedValues;
let different = false;
return Promise.map(instances, instance => {
return Promise.all(instances.map(instance => {
// Record updates in instances dataValues
Object.assign(instance.dataValues, values);
// Set the changed fields on the instance
......@@ -3177,7 +3174,7 @@ class Model {
return instance;
});
}).then(_instances => {
})).then(_instances => {
instances = _instances;
if (!different) {
......@@ -3192,14 +3189,14 @@ class Model {
}
// Hooks change values in a different way for each record
// Do not run original query but save each record individually
return Promise.map(instances, instance => {
return Promise.all(instances.map(instance => {
const individualOptions = _.clone(options);
delete individualOptions.individualHooks;
individualOptions.hooks = false;
individualOptions.validate = false;
return instance.save(individualOptions);
}).tap(_instances => {
})).tap(_instances => {
instances = _instances;
});
});
......@@ -3234,9 +3231,9 @@ class Model {
});
}).tap(result => {
if (options.individualHooks) {
return Promise.map(instances, instance => {
return Promise.all(instances.map(instance => {
return this.runHooks('afterUpdate', instance, options);
}).then(() => {
})).then(() => {
result[1] = instances;
});
}
......@@ -3722,11 +3719,10 @@ class Model {
!options.raw &&
(
// True when sequelize method
value instanceof Utils.SequelizeMethod ||
(value instanceof Utils.SequelizeMethod ||
// Check for data type type comparators
!(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeChanges[key] && this.constructor._dataTypeChanges[key].call(this, value, originalValue, options) ||
// Check default
!this.constructor._dataTypeChanges[key] && !_.isEqual(value, originalValue)
!(value instanceof Utils.SequelizeMethod) && this.constructor._dataTypeChanges[key] && this.constructor._dataTypeChanges[key].call(this, value, originalValue, options) || // Check default
!this.constructor._dataTypeChanges[key] && !_.isEqual(value, originalValue))
)
) {
this._previousDataValues[key] = originalValue;
......@@ -3986,7 +3982,7 @@ class Model {
if (!this._options.include || !this._options.include.length) return this;
// Nested creation for BelongsTo relations
return Promise.map(this._options.include.filter(include => include.association instanceof BelongsTo), include => {
return Promise.all(this._options.include.filter(include => include.association instanceof BelongsTo).map(include => {
const instance = this.get(include.as);
if (!instance) return Promise.resolve();
......@@ -3999,7 +3995,7 @@ class Model {
}).value();
return instance.save(includeOptions).then(() => this[include.association.accessors.set](instance, { save: false, logging: options.logging }));
});
}));
}).then(() => {
const realFields = options.fields.filter(field => !this.constructor._virtualAttributes.has(field));
if (!realFields.length) return this;
......@@ -4058,8 +4054,8 @@ class Model {
if (!this._options.include || !this._options.include.length) return this;
// Nested creation for HasOne/HasMany/BelongsToMany relations
return Promise.map(this._options.include.filter(include => !(include.association instanceof BelongsTo ||
include.parent && include.parent.association instanceof BelongsToMany)), include => {
return Promise.all(this._options.include.filter(include => !(include.association instanceof BelongsTo ||
include.parent && include.parent.association instanceof BelongsToMany)).map(include => {
let instances = this.get(include.as);
if (!instances) return Promise.resolve();
......@@ -4075,7 +4071,7 @@ class Model {
}).value();
// Instances will be updated in place so we can safely treat HasOne like a HasMany
return Promise.map(instances, instance => {
return Promise.all(instances.map(instance => {
if (include.association instanceof BelongsToMany) {
return instance.save(includeOptions).then(() => {
const values = {};
......@@ -4102,8 +4098,8 @@ class Model {
instance.set(include.association.foreignKey, this.get(include.association.sourceKey || this.constructor.primaryKeyAttribute, { raw: true }), { raw: true });
Object.assign(instance, include.association.scope);
return instance.save(includeOptions);
});
});
}));
}));
})
.tap(result => {
// Run after hook
......
......@@ -98,7 +98,9 @@ class QueryInterface {
if (!this.QueryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options);
}
return this.showAllSchemas(options).map(schemaName => this.dropSchema(schemaName, options));
return this.showAllSchemas(options).then(schemas => Promise.all(
schemas.map(schemaName => this.dropSchema(schemaName, options))
));
}
/**
......@@ -368,9 +370,11 @@ class QueryInterface {
options = options || {};
return this.pgListEnums(null, options).map(result => this.sequelize.query(
return this.pgListEnums(null, options).then(enums => Promise.all(
enums.map(result => this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
Object.assign({}, options, { raw: true })
))
));
}
......@@ -689,9 +693,8 @@ class QueryInterface {
options = Object.assign({}, options || {}, { type: QueryTypes.FOREIGNKEYS });
return Promise.map(tableNames, tableName =>
this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options)
).then(results => {
return Promise.all(tableNames.map(tableName =>
this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options))).then(results => {
const result = {};
tableNames.forEach((tableName, i) => {
......
......@@ -854,7 +854,7 @@ class Sequelize {
if (options && options.cascade) {
return Promise.each(models, truncateModel);
}
return Promise.map(models, truncateModel);
return Promise.all(models.map(truncateModel));
}
/**
......
......@@ -78,6 +78,7 @@
"mocha": "^6.1.4",
"mysql2": "^1.6.5",
"nyc": "^15.0.0",
"p-map": "^4.0.0",
"pg": "^7.8.1",
"pg-hstore": "^2.x",
"pg-types": "^2.0.0",
......
......@@ -764,7 +764,7 @@ describe(Support.getTestDialectTeaser('HasOne'), () => {
dataTypes = [Sequelize.INTEGER, Sequelize.BIGINT, Sequelize.STRING],
Tasks = {};
return Promise.map(dataTypes, dataType => {
return Promise.all(dataTypes.map(dataType => {
const tableName = `TaskXYZ_${dataType.key}`;
Tasks[dataType] = this.sequelize.define(tableName, { title: Sequelize.STRING });
......@@ -773,7 +773,7 @@ describe(Support.getTestDialectTeaser('HasOne'), () => {
return Tasks[dataType].sync({ force: true }).then(() => {
expect(Tasks[dataType].rawAttributes.userId.type).to.be.an.instanceof(dataType);
});
});
}));
});
describe('allows the user to provide an attribute definition object as foreignKey', () => {
......
......@@ -527,9 +527,9 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return promise;
})([B, C, D, E, F, G, H])
).then(([as, b]) => {
return Promise.map(as, a => {
return Promise.all(as.map(a => {
return a.setB(b);
});
}));
}).then(() => {
return A.findAll({
include: [
......@@ -625,9 +625,9 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return promise;
})([B, C, D, E, F, G, H])
).then(([as, b]) => {
return Promise.map(as, a => {
return Promise.all(as.map(a => {
return a.setB(b);
});
}));
}).then(() => {
return A.findAll({
include: [
......@@ -970,9 +970,9 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return Promise.join(
results.users[0].setGroup(results.groups[1]),
results.users[1].setGroup(results.groups[0]),
Promise.map(results.groups, group => {
Promise.all(results.groups.map(group => {
return group.setCategories(results.categories);
})
}))
);
}).then(() => {
return User.findAll({
......@@ -1023,9 +1023,9 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return Promise.join(
results.users[0].setTeam(results.groups[1]),
results.users[1].setTeam(results.groups[0]),
Promise.map(results.groups, group => {
Promise.all(results.groups.map(group => {
return group.setTags(results.categories);
})
}))
);
}).then(() => {
return User.findAll({
......@@ -1076,9 +1076,9 @@ describe(Support.getTestDialectTeaser('Include'), () => {
return Promise.join(
results.users[0].setGroup(results.groups[1]),
results.users[1].setGroup(results.groups[0]),
Promise.map(results.groups, group => {
Promise.all(results.groups.map(group => {
return group.setCategories(results.categories);
})
}))
);
}).then(() => {
return User.findAll({
......@@ -1698,9 +1698,9 @@ describe(Support.getTestDialectTeaser('Include'), () => {
Post.create({ 'public': true }),
Post.create({ 'public': true })
).then(posts => {
return Promise.map(posts.slice(1, 3), post => {
return Promise.all(posts.slice(1, 3).map(post => {
return post.createCategory({ slug: 'food' });
});
}));
}).then(() => {
return Post.findAll({
limit: 2,
......
......@@ -12,7 +12,8 @@ const chai = require('chai'),
Promise = require('bluebird'),
current = Support.sequelize,
Op = Sequelize.Op,
semver = require('semver');
semver = require('semver'),
pMap = require('p-map');
describe(Support.getTestDialectTeaser('Model'), () => {
before(function() {
......@@ -2467,7 +2468,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
for (let i = 0; i < 1000; i++) {
tasks.push(testAsync);
}
return Sequelize.Promise.resolve(tasks).map(entry => {
return pMap(tasks, entry => {
return entry();
}, {
// Needs to be one less than ??? else the non transaction query won't ever get a connection
......
......@@ -201,14 +201,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
return User.sync({ force: true }).then(() => {
return Promise.map(_.range(50), i => {
return Promise.all(_.range(50).map(i => {
return User.findOrCreate({
where: {
email: `unique.email.${i}@sequelizejs.com`,
companyId: Math.floor(Math.random() * 5)
}
});
});
}));
});
});
......@@ -225,22 +225,22 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
return User.sync({ force: true }).then(() => {
return Promise.map(_.range(50), i => {
return Promise.all(_.range(50).map(i => {
return User.findOrCreate({
where: {
email: `unique.email.${i}@sequelizejs.com`,
companyId: 2
}
});
}).then(() => {
return Promise.map(_.range(50), i => {
})).then(() => {
return Promise.all(_.range(50).map(i => {
return User.findOrCreate({
where: {
email: `unique.email.${i}@sequelizejs.com`,
companyId: 2
}
});
});
}));
});
});
});
......@@ -258,14 +258,14 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
return User.sync({ force: true }).then(() => {
return Promise.map(_.range(50), () => {
return Promise.all(_.range(50).map(() => {
return User.findOrCreate({
where: {
email: 'unique.email.1@sequelizejs.com',
companyId: 2
}
});
});
}));
});
});
}
......
......@@ -1173,7 +1173,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
it('sorts simply', function() {
return Sequelize.Promise.map([['ASC', 'Asia'], ['DESC', 'Europe']], params => {
return Sequelize.Promise.all([['ASC', 'Asia'], ['DESC', 'Europe']].map(params => {
return this.Continent.findAll({
order: [['name', params[0]]]
}).then(continents => {
......@@ -1181,11 +1181,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(continents[0]).to.exist;
expect(continents[0].name).to.equal(params[1]);
});
});
}));
});
it('sorts by 1st degree association', function() {
return Sequelize.Promise.map([['ASC', 'Europe', 'England'], ['DESC', 'Asia', 'Korea']], params => {
return Sequelize.Promise.all([['ASC', 'Europe', 'England'], ['DESC', 'Asia', 'Korea']].map(params => {
return this.Continent.findAll({
include: [this.Country],
order: [[this.Country, 'name', params[0]]]
......@@ -1197,11 +1197,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(continents[0].countries[0]).to.exist;
expect(continents[0].countries[0].name).to.equal(params[2]);
});
});
}));
});
it('sorts simply and by 1st degree association with limit where 1st degree associated instances returned for second one and not the first', function() {
return Sequelize.Promise.map([['ASC', 'Asia', 'Europe', 'England']], params => {
return Sequelize.Promise.all([['ASC', 'Asia', 'Europe', 'England']].map(params => {
return this.Continent.findAll({
include: [{
model: this.Country,
......@@ -1225,11 +1225,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(continents[1].countries[0]).to.exist;
expect(continents[1].countries[0].name).to.equal(params[3]);
});
});
}));
});
it('sorts by 2nd degree association', function() {
return Sequelize.Promise.map([['ASC', 'Europe', 'England', 'Fred'], ['DESC', 'Asia', 'Korea', 'Kim']], params => {
return Sequelize.Promise.all([['ASC', 'Europe', 'England', 'Fred'], ['DESC', 'Asia', 'Korea', 'Kim']].map(params => {
return this.Continent.findAll({
include: [{ model: this.Country, include: [this.Person] }],
order: [[this.Country, this.Person, 'lastName', params[0]]]
......@@ -1244,11 +1244,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(continents[0].countries[0].people[0]).to.exist;
expect(continents[0].countries[0].people[0].name).to.equal(params[3]);
});
});
}));
});
it('sorts by 2nd degree association with alias', function() {
return Sequelize.Promise.map([['ASC', 'Europe', 'France', 'Fred'], ['DESC', 'Europe', 'England', 'Kim']], params => {
return Sequelize.Promise.all([['ASC', 'Europe', 'France', 'Fred'], ['DESC', 'Europe', 'England', 'Kim']].map(params => {
return this.Continent.findAll({
include: [{ model: this.Country, include: [this.Person, { model: this.Person, as: 'residents' }] }],
order: [[this.Country, { model: this.Person, as: 'residents' }, 'lastName', params[0]]]
......@@ -1263,11 +1263,11 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(continents[0].countries[0].residents[0]).to.exist;
expect(continents[0].countries[0].residents[0].name).to.equal(params[3]);
});
});
}));
});
it('sorts by 2nd degree association with alias while using limit', function() {
return Sequelize.Promise.map([['ASC', 'Europe', 'France', 'Fred'], ['DESC', 'Europe', 'England', 'Kim']], params => {
return Sequelize.Promise.all([['ASC', 'Europe', 'France', 'Fred'], ['DESC', 'Europe', 'England', 'Kim']].map(params => {
return this.Continent.findAll({
include: [{ model: this.Country, include: [this.Person, { model: this.Person, as: 'residents' }] }],
order: [[{ model: this.Country }, { model: this.Person, as: 'residents' }, 'lastName', params[0]]],
......@@ -1283,7 +1283,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(continents[0].countries[0].residents[0]).to.exist;
expect(continents[0].countries[0].residents[0].name).to.equal(params[3]);
});
});
}));
});
});
......
......@@ -250,7 +250,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
let count = 0;
return this.User.bulkCreate([{ username: 'jack' }, { username: 'jack' }]).then(() => {
return Sequelize.Promise.map(permutations, perm => {
return Sequelize.Promise.all(permutations.map(perm => {
return this.User.findByPk(perm, {
logging(s) {
expect(s).to.include(0);
......@@ -259,7 +259,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
}).then(user => {
expect(user).to.be.null;
});
});
}));
}).then(() => {
expect(count).to.be.equal(permutations.length);
});
......
......@@ -148,7 +148,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
it('should merge complex scopes correctly regardless of their order', function() {
return Promise.map(this.scopePermutations, scopes => this.Foo.scope(...scopes).findOne()).then(results => {
return Promise.all(this.scopePermutations.map(scopes => this.Foo.scope(...scopes).findOne())).then(results => {
const first = results.shift().toJSON();
for (const result of results) {
expect(result.toJSON()).to.deep.equal(first);
......@@ -157,7 +157,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
it('should merge complex scopes with findAll options correctly regardless of their order', function() {
return Promise.map(this.scopePermutations, ([a, b, c, d]) => this.Foo.scope(a, b, c).findAll(this.scopes[d]).then(x => x[0])).then(results => {
return Promise.all(this.scopePermutations.map(([a, b, c, d]) => this.Foo.scope(a, b, c).findAll(this.scopes[d]).then(x => x[0]))).then(results => {
const first = results.shift().toJSON();
for (const result of results) {
expect(result.toJSON()).to.deep.equal(first);
......@@ -166,7 +166,7 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
it('should merge complex scopes with findOne options correctly regardless of their order', function() {
return Promise.map(this.scopePermutations, ([a, b, c, d]) => this.Foo.scope(a, b, c).findOne(this.scopes[d])).then(results => {
return Promise.all(this.scopePermutations.map(([a, b, c, d]) => this.Foo.scope(a, b, c).findOne(this.scopes[d]))).then(results => {
const first = results.shift().toJSON();
for (const result of results) {
expect(result.toJSON()).to.deep.equal(first);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!