What's wrong with this function? Returns return undefined

0

I want to make a function that returns the data of this process but I am not achieving it since when executing it and sending it an id it returns undefined

var getData = function(id) {
  db.collection('users').doc(id).get()
  .then(function(doc) {
  if (doc.exists) {
      return doc.data();
  } else {
    return 'Document not found';
  }
}).catch(function(error) {
  return error;
});
}
    
asked by Santiago D'Antuoni 23.01.2018 в 20:48
source

1 answer

2

Since you are requesting an asynchronous resource you need to handle it in the same way, it is not possible for the promise to run synchronously, that is why I propose a solution to the problem:

  

It is likely that many more changes in the code will be needed for the following to work correctly, I only intend to show how the process should be done.

var getData = function (id) {
  return new Promise(function (resolve, reject) {
    db.collection('users').doc(id).get()
      .then(function (doc) {
        if (doc.exists) {
          resolve(doc.data());
        }

        reject('Document not found');
      })
      .catch(function (exception) {
        reject(exception);
      })
  });
}

var id = 6;

getData(id).then(function (data) {
  console.log('Datos:', data);
  // Proceso a realizar
}).catch(function (exception) {
  console.error('Exeption:', exception);
});

Documentation of the Promises

    
answered by 23.01.2018 / 21:06
source