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');

var promise = Q.fcall(function () {
return "Fixed value";
});

promise.then(function (val) {
console.log(val);
});

Using a deferred object

You can also use the traditional deferred object and resolve it immediately.

var promise = function () {

var deferred = Q.defer(); // Create a deferred object

deferred.resolve("Fixed Value"); // Resolve it

return deferred.promise; // Return a promise
}(); // function is self invoking

promise.then(function (value) {
console.log(value);
});

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) {

return resolve("Fixed Value");
});

promise.then(function (value) {
console.log(value);
});