【问题标题】:Return a promise on an external function with async data returned from an inner function使用从内部函数返回的异步数据返回外部函数的承诺
【发布时间】:2016-08-08 06:22:34
【问题描述】:

我正在设计一个用户API,部分API代码如下:

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

我的意图是让findByEmail 返回一个承诺,以便可以调用它,例如:

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

但是,像上面这样定义我的 API 并不能实现我想要的,因为内部函数是返回承诺的函数,而外部函数(即findByEmail)最终不会返回承诺。如何确保外部函数使用内部函数返回的数据返回承诺?

当然,使外部函数接受回调是一种选择,但这意味着外部函数不再是可承诺的。

【问题讨论】:

    标签: javascript promise ecmascript-6 es6-promise


    【解决方案1】:

    这里我调用了listings(),在得到响应后调用了jquery ajax,我将promise返回给从外部文件调用的函数getlistings()

    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);
    });
    
    }
    

    【讨论】:

      【解决方案2】:

      先返回 Promise,然后让 Promise 回调函数完成剩下的工作。

      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);
            }
          }
        }
      }
      

      【讨论】:

      • 哦,是的!不敢相信我错过了这个:|
      • @AlexanderMac 在此示例中不需要。一个承诺只能被解决或拒绝once。为了清楚起见,有些人可能更愿意在那里看到返回,正确执行不需要它。如果有任何额外的处理,当然需要退货。
      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 2020-01-11
      相关资源
      最近更新 更多