Problem with promise when collecting values that returns

0

Within a function, I need to call another in which I have used promises and return a series of data that I need to follow.

My problem is that I do not know if I'm doing it right or not, because does not throw an error but it returns an empty object. If I show it with console.log, it returns: Object Promise

The code is:

getData: function (results) {

    return new Promise(function (resolve, reject) {

      Common.getProvider(results).then(function(provider) {

          provider.getData().then(function (providerData) {
              var name = providerData.name;
              var type = providerData.type;
              var lang = providerData.language;

              var data = [];
              data.push(name);
              data.push(type);
              data.push(lang);

              resolve(data);
            },
            function (error) {
              reject(error);
              console.log("Error 1", error);
            }
          );
        },
        function (error) {
          console.log("Error 2", error);
          reject(error);
        })
      .catch(
        function (error) {
          console.log("Error catch", error);
          reject(error);
        });
    });

},

And in the next function I need to work with that data (data):

extractData: function(results) {

var resultsPDF = [];
var resultsImg = [];

for (var i = 0; i < results.length; i++) {
  if (results[i].fileMimeType == "application/pdf") {
    resultsPDF.push(results[i]);
  }
  else {
    resultsImg.push(results[i]);
  }
}

if (resultsPDF.length > 0) {

  var datosQnecesito = Controller.getData(resultsPDF);
  console.log("DATOS = "+ datosQnecesito); //Devuelve Object Promise
  console.log(JSON.stringify(prov)); //Devuelve {}

  //A partir de aquí necesitaré trabajar con esos datos que recibo
  //...
  }
}

How do I collect the data that returns the promise correctly so I can later work with them?

If there is an alternative way to do it, you can also help me

    
asked by Norak 15.11.2017 в 10:57
source

2 answers

1

We already know that getData returns a promise, so the call to

var datosQnecesito = Controller.getData(resultsPDF);

Does not contain the data. It contains a promise, and you want the value that will come when the promise is resolved. Therefore it should be:

Controller.getData(resultsPDF)
 .then(function(datosQnecesito) {
     console.log("DATOS = ", datosQnecesito); 
     //A partir de aquí necesitaré trabajar con esos datos que recibo
     //...
 });

I have no idea what prov will be so I did not put it in the example code.

Having said that, there are two things that I would improve and I feel compelled to comment on them:

First , I would tell you that your getData function is using then(success,fail) which is a type of anti-pattern , because it misses the native behavior of promises by using them as if they were callbacks.

Second , for this case you do not really need to use a promise builder to wrap everything up. That too is another antipattern in your situation.

I would rewrite getData as:

getData: function (results) {

  return  Common.getProvider(results)
    .then(function (provider) {

        return provider.getData();

    }).then(function (providerData) {
      var name = providerData.name;
      var type = providerData.type;
      var lang = providerData.language;
      var data = [];

      data.push(name);
      data.push(type);
      data.push(lang);

      return data;

    });
},

Common.getProvider is in itself a promise. You can return it as is.

Now, if you rewrite the code as I am showing you, you will see that I am not capturing a possible error. Another grace of the promises is that any intermediate error will propagate to the first catch (or else it will throw an error Unhandled Rejection ). That means that you do not need to put a catch on each promise, because that would be just as inefficient as the old method of callbacks. Let the promises work for you.

Simply put a single catch in the function that calls the promise:

Controller.getData(resultsPDF)
 .then(function(datosQnecesito) {
     console.log("DATOS = ", datosQnecesito); 
     //A partir de aquí necesitaré trabajar con esos datos que recibo
     //...
 }).catch(function(err) {
    console.error(err);
 });

And that will catch any error that has occurred in getData . Within getData you do not have to use throw . That would make promises-again-just a different way of writing with callbacks. As Petka Antonov writes: Promise returning functions should never throw .

    
answered by 15.11.2017 / 11:39
source
2

What I do not think you understand is the concept of "promise". Promises are elements that are used to execute code asynchronously, that is, code whose result is not going to be obtained at the moment.

You can not invoke a promise and use the result of it in the following statement. What you do with the promises is to pass them a function with the code that you want to execute with the result of it, at the moment in which it is obtained.

In your case it would be something like this:

var promesa = Controller.getData(resultsPDF);
promesa.then(function(datosQnecesito) {
  console.log('DATOS = ' + datosQnecesito);
});
    
answered by 15.11.2017 в 11:38