Brian Brian - 3 months ago 23
Javascript Question

Sending data between jquery deferred objects

I'm trying to grasp deferred objects in jquery but keep running in trouble. Basically I have a series of functions I want to run where the result from function 1 dictates the logic in a second function.

I'm not sure if I have to invoke a pipe method somewhere or just use then() but either way I keep failing. If you look at the first function there is a object named data which is I want to pass to the second.

function run() {
var data1 = {};
var data2 = {};

var body = $('body');


function first() {
var d = new $.Deferred();

var data = {} //arbitrary data set that i want to send to second

data.message = 'first message'; = 1234;

body.append('First done');

//return data object? add it to the resolve method?

function second(data) { //how do I get this data object?

var d = new $.Deferred();

body.append('Data from first:');

body.append('Second done');

function constructData() {




Here is a simplified, live demo of your example:

What is missing in your code:

1/ you need to pass in resolve the argument for the second function:


2/ you need to return the deferred:

return d;

Note: in practice you would return the deferred before it is resolved (hence the name). Also, the deferred is built in some methods like ajax calls.