This is a code example taken from Perfect Swift PostgresSTORM library.
do{
//Create a user object
let obj = User()
obj.name = "someUser"
//Save it to db
try obj.save({ id in
print(2..)
obj.id = id as! Int
})
print("1..")
}catch{
print("Something went wrong.")
}
//Go to next page
print("3..")
I expected to see the print logs to be 1.. 3.. 2..
but, The logs looked like this. 2.. 1.. 3..
It's highly unlikely for "2.." to print before "1..". Is it the "try" that's making it to run as a synchronous function?
It's totally up to PostgresSTORM implementation of
save
. I'm not familiar with it so I can't say whether it's actually asynchronous or not but I can offer you two dummy implementations, one asynchronous and one synchronous of a method with a similar signature.Asynchronous:
Synchronous:
(Note that it doesn't throw any exception in this example just for simplicity's sake).
try
is required by Swift compiler when you call a function that might throw an exception and has no impact in (a)synchronous execution of the method. In facttry
is just required to ensure that when we use the method we are well aware about it possibly throwing an exception.I might be wrong but if this is SwiftORM's implementation of
save
method then callback is always synchronously called.