简体   繁体   中英

Return a promise on an external function with async data returned from an inner function

I'm designing a user API and part of the API code is as follows:

module.exports = {
  findByEmail: (email) => {
    db.collection('Users').findOne(email: email), (err, result) => {
      assert.equal(err, null);
      return new Promise(resolve) => {
        resolve(result);
      }
    }
  }
}

My intention here is to make findByEmail return a promise so that it can be invoked such as:

require('./models/User').findByEmail({email: 'user@example.com'})
.then((user) => {
  console.log('User account', user);
});

However defining my API like above does not achieve what I want, since the inner function is the one that returns the promise, while the external function (ie findByEmail ) ends up not returning a promise. How do I make sure that the external function returns a promise using the data returned by the inner function?

Of course, making the external function accept a callback is an option, but this would mean that the external function is not promisifiable anymore.

Return the promise first, then let the promise call-back function do the rest.

module.exports = {
  findByEmail: (email) => {
    return new Promise((resolve, reject) => {
      db.collection('Users').findOne(email: email), (err, result) => {
        //   assert.equal(err, null);
        if (err) {
          reject(err);
        }
        resolve(result);
      }
    }
  }
}

Here Im calling the listings()in which jquery ajax call is made after getting the response i returned the promise to a function getlistings() which is called from an external file

function Listings(url){

var deferred = new $.Deferred();
$.ajax({
    url: url,
    method: 'GET',
    contentType: 'application/json',
    success: function (response) {
        deferred.resolve(response);
    },
    error: function (response){
        deferred.reject(response);
    }
});
return deferred.promise();  
};

// call from external file

function getListings(){
Listings('/listings.json').then(function(response){

 console.log(response);
});

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM