0

I have this code written in AngularJS. I am not able to synchronize this. I want to resolve myData value before reaching if condition. But my code flow continues and It doesn't goes into 'IF' condition, because at that point myData is a promise function.

function() {
    var dfd = $q.defer();

var myData = false; 
var myData = restResource.get(itemId).queryOptions(options).promise().then(function(dataItem1) {
    return restResource.oneAction(dataItem1.elements).then(function(dataItem2) {
        var i;
        if (dataItem2.items.length > 0) {
            dfd.resolve(true);
            return dfd.promise;
        }
    });
});

if(myData === true) {
    dfd.resolve(item.attributes);
    return dfd.promise;
}

//Another Resource call... code continues...
}

Also I tried to use $q.defer, but I think I am doing something wrong.

Let me know what is missing here.

Cœur
  • 37,241
  • 25
  • 195
  • 267
IfOnly
  • 540
  • 1
  • 4
  • 17

1 Answers1

1

Promises do not magically make async code synchronous. They are still asynchronous and use callbacks. In your case, myData will never be a boolean, because it is asynchronously obtained - but you can get a promise for it. The if-statement must go in a callback.

function() {
    return restResource.get(itemId).queryOptions(options).promise()
    .then(function(dataItem1) {
        return restResource.oneAction(dataItem1.elements);
    }) // here we can unnest!
    .then(function(dataItem2) {
        var myData;
        if (dataItem2.items.length > 0) {
            myData = true
            // item.attributes;
        }

        //Another Resource call... code continues...
    });
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375