#Promise #Asynchronous #then #beer #wife velo
In Velo, there are a number of cases where code is not necessarily executed sequentially. This is called asynchronous code execution. Velo uses Promises to handle asynchronous code. Web modules, fetches (wix-fetch), and database queries, are some of the places where you will need to handle Promises.
This may sound complicated or a bit weird, but the concept of Promises is actually really quite simple. Look at it this way…
-
My wife asks me to take out the trash :: the request or query
-
I say, “yes dear” :: the promise
-
The wife of course doesn’t expect this to happen any time soon, so immediately after the promise she keeps on doing whatever it is she’s doing.
-
Eventually (after I’ve had a beer or two) I take out the trash which is the fulfillment , or .then() , of the promise .
Let’s look at some loosely defined pseudo-code to see how this might work in Javascript:
let promise = request(“take out the trash”);
let status = full;
promise.then(function(result) {
status = result; // result = empty
console.log(status); // “empty”
}, function(err) {
// “fatal” error - fell asleep after the fourth or fifth beer
console.log(err); // Error: “wife stomps angrily around house"
});
console.log(status); // still “full"
As you can see, if my wife was to do a console.log(status) directly after I promise to take out the trash, the trash can would show up full (probably for a considerable period of time). However, after I’ve had a few beers, I take out the trash and my promise has been fulfilled. That is, we are now in the .then() handler and console.log(status) shows the trash can is empty.
I hope this helps. And don’t tell my wife - although I suspect she already knows.
For further details, see the article Velo: Working with Promises.