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.

1
2
3
4
5
6
7
8
9
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.

1
2
3
4
5
6
7
8
9
10
11
12
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.

1
2
3
4
5
6
7
8
var promise = Q.promise(function(resolve) {

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

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