Brian Brian - 2 months ago 12
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');

$.when(first()).then(second()).done(constructData);

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



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

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

body.append('First done');

//return data object? add it to the resolve method?
d.resolve();
}

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

var d = new $.Deferred();


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

body.append('Second done');

d.resolve();
}
function constructData() {

}

}

Answer

Here is a simplified, live demo of your example: http://jsfiddle.net/L96cD/

What is missing in your code:

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

d.resolve(data);

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.

Comments