0

I have following controller and code execution does not wait for the function to bring back values. So some lines of code fail as they are still undefined. How to make sure line execution is in sync.

Also Note: caller function is inside a for loop.

A Controller.js

for (var i=0; i< parseObj.length; i++){
callerFunc: function() {
    vc._getValues(A, B, C).then(function (data) {
                    var vendorNo = data.vendorNo;
                    var vendorName = data.vendorName
            });
      // lines of code

}


  _getValues: function(A, B, C){
    var filters = [
            .....
        ];
        var vc = this;
        return new Promise(function (resolve, reject) {
            service.getDataByFilters(vc, filters,
                function (data) {
                    resolve(data);
                },
                function (error) {
                    reject();
                }
            );
        });
THI
  • 355
  • 11
  • 40

1 Answers1

1

the problem is that you need to wait for the result. Service.getMaterial is returning a Promise so when you try to execute the line of code var x = data.Vendor; the variable data is not yet defined.

What you can do is to just call a function inside the promise result (the then function).

I would suggest you learn a little bit more about:

  1. Promise
  2. async/await pattern

I also would like you to know that promise/async-await are not supported by IE in general if I'm not wrong ;)

StErMi
  • 5,389
  • 5
  • 48
  • 71
  • I have made changes to my code using Promise concept, but now the control never goes to the statements after then.... it just goes to all other lines of code below. What could be the issue? – THI Jan 16 '19 at 17:50