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() {
}
}
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() {
}
}
Share
Improve this question
edited Oct 4, 2016 at 14:53
Subodh Ghulaxe
18.7k15 gold badges86 silver badges103 bronze badges
asked Mar 1, 2013 at 6:07
BrianBrian
4,41814 gold badges63 silver badges105 bronze badges
1 Answer
Reset to default 6Here is a simplified, live demo of your example: http://jsfiddle/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.