Search code examples
javascriptjquerybackbone.jsfetchdeferred

$.when with multiple fetch() breaks backbone model


I am trying to use $.when() in my project.
If I write something like:

    var getTaskInfo = new Task({'id': task_id}).fetch();

    $.when(getTaskInfo).then(function (obj1) {
        console.log(obj1);
    });

console output gives me:

Object {id: 1, task_type_id: "1", project_id: "1", order_in_project: 1, main_answer_id: "1"…}

and all works fine

but when I try to use multiple fetches()

    var getTaskInfo = new Task({'id': task_id}).fetch();
    var getAllAnswers = new TaskAnswers(null, {'task_id': task_id}).fetch();

    $.when(getTaskInfo, getAllAnswers).then(function (obj1, obj2) {
        console.log(obj1);
    });

console output shows me that obj1 now is:

[Object, "success", Object]
0: Object
1: "success"
2: Object
length: 3

That isn't object I am waiting for.
What I am doing wrong? I just expect that obj1 gives me output like it was in first case.


Solution

  • Try accessing objects at .then()

    $.when(getTaskInfo, getAllAnswers).then(function (obj1, obj2) {
        console.log(obj1[0], obj2[0]);
    });