5.5 Promises with multiple consumers

Sometimes we need to consume the result of an asynchronous operation from two or more pieces of code. In that case we say that a promise has multiple consumers.

Getting Ready

All you need to implement in this recipe is an installation of TypeScript 2.0 or higher and jQuery.

How to do it

When two or more pieces of code need to consume the result of an asynchronous operation we can share a promise between them. The following example declares a function named getProfileAsync. This function returns a promise that returns the details of a user profile when fulfilled:

import * as Promise from 'bluebird';
import * as $ from 'jquery';

interface IUserProfile {
	name : string,
	surname : string,
	website : string,
	twitter : string
}

function getProfileAsync() {
	return new Promise((resolve, reject) => {
		$.ajax({
			url: '/data/user_profile.json',
			async : true,
			method: "GET",
			dataType : "json",
			success: function(data : IUserProfile) {
				resolve(data);
			},
			error : function(e) {
				reject(e);
			}
		});
	});
}

We can then obtain one single promise and share it with other pieces of code:

function renderMenuBar(profilePromise) {
	profilePromise.then((data : IUserProfile) => {
		$("#user_name").html(data.name);
	}).catch((e) => { 
		console.log(e);
	});
}

function renderAccountPage(profilePromise) {
	profilePromise.then((data : IUserProfile) => {
		$("#user_name").html(data.name);
		$("#user_surname").html(data.surname);
		$("#user_website").html(data.website);
		$("#user_twitter").html(data.twitter);
	}).catch((e) => { 
		console.log(e);
	});
}

const profilePromise = getProfileAsync();
renderMenuBar(profilePromise);
renderAccountPage(profilePromise);

How it works

The preceding code snippet declared two functions named renderMenuBar and renderAccountPage. These two functions need to access the result of a promise to display some details on screen. We can achieve this by passing the promise to both functions.

Source Code

Promises with multiple consumers

See also

Please refer to the other recipes about promises in this chapter to learn about more Bluebird and the promises API.


Shiv Kushwaha

Author/Programmer