Promises are usually used as an elegant way to handle asynchronous operations. In this article, we will look at how to create promises from fixed values and non asynchronous operations. For example you have a function that returns a value and you need to promisify it.
I will be using node and the Q library for these examples.
Using Q.fcall
The simplest and most straight forward way to go is to use Q.fcall to generate a promise from a function that returns a fixed value.
var Q = require('q'); |
Using a deferred object
You can also use the traditional deferred object and resolve it immediately.
var promise = function () { |
Using Q.Promise
Finally you can also use Q.Promise which is a different take on the deferred: different syntax but same level of control.
var promise = Q.promise(function(resolve) { |