我有代码,在将图像保存到集合之前裁剪图像,但代码是异步执行的。在裁剪图像之前执行插入到集合。
Meteor.methods({
'createWorkout': function(workoutFormContent, fileObj) {
// crop image to width:height = 3:2 aspect ratio
var workoutImage = gm(fileObj.path);
workoutImage.size(function(error, size) {
if (error) console.log(error);
height = size.height;
width = size.height * 1.5;
workoutImage
.gravity("Center")
.crop(width, height)
.write(fileObj.path, function(error) {
if (error) console.log(error)
});
});
// add image to form content and insert to collection
workoutFormContent.workoutImage = fileObj;
Workouts.insert(workoutFormContent, function(error) {
if (error) {
console.log(error);
}
});
},
});
如何同步运行此代码才能插入已裁剪的图像?
答案 0 :(得分:1)
仅在裁剪图像后写入集合:
var physics = Array<UInt32>()
struct PhysicsCategory{
static let square1 : UInt32 = 0x1 << 1
static let square2 : UInt32 = 0x1 << 2
static let square3 : UInt32 = 0x1 << 3
static let square4 : UInt32 = 0x1 << 4
static let square5 : UInt32 = 0x1 << 5
static let square6 : UInt32 = 0x1 << 6
static let square7 : UInt32 = 0x1 << 7
static let square8 : UInt32 = 0x1 << 8
static let square9 : UInt32 = 0x1 << 9
}
override func didMove(to view: SKView) {
physics.append(PhysicsCategory.square1)
physics.append(PhysicsCategory.square2)
physics.append(PhysicsCategory.square3)
physics.append(PhysicsCategory.square4)
physics.append(PhysicsCategory.square5)
physics.append(PhysicsCategory.square6)
physics.append(PhysicsCategory.square7)
physics.append(PhysicsCategory.square8)
physics.append(PhysicsCategory.square9)
for i in (0...8){
squares[i].node.physicsBody = SKPhysicsBody(rectangleOf: squares[i].node.size )
squares[i].node.physicsBody?.categoryBitMask = physics[i]
squares[i].node.physicsBody?.affectedByGravity = false
squares[i].node.physicsBody?.isDynamic = false
squares[i].node.physicsBody?.contactTestBitMask = PhysicsCategory.Circle
squares[i].node.physicsBody?.collisionBitMask = 0
}
}
或者使用import { Meteor } from 'meteor/meteor';
import gm from 'gm';
const bound = Meteor.bindEnvironment((callback) => {callback();});
Meteor.methods({
createWorkout(workoutFormContent, fileObj) {
// crop image to width:height = 3:2 aspect ratio
const workoutImage = gm(fileObj.path);
workoutImage.size((error, size) => {
bound(() => {
if (error) {
console.log(error);
return;
}
const height = size.height;
const width = size.height * 1.5;
workoutImage.gravity('Center').crop(width, height).write(fileObj.path, (writeError) => {
bound(() => {
if (writeError) {
console.log(writeError);
return;
}
// add image to form content and insert to collection
workoutFormContent.workoutImage = fileObj;
Workouts.insert(workoutFormContent, (insertError) => {
if (insertError) {
console.log(insertError);
}
});
});
});
});
});
}
});
lib,它可用于阻止事件循环。