簡體   English   中英

使用內部函數返回的異步數據返回外部函數的promise

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

我正在設計用戶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返回一個promise,以便可以調用它,例如:

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

然而,如上所述定義我的API並沒有實現我想要的,因為內部函數是返回promise的函數,而外部函數(即findByEmail )最終沒有返回promise。 如何確保外部函數使用內部函數返回的數據返回一個promise?

當然,使外部函數接受回調是一種選擇,但這意味着外部函數不再具有可承諾性。

首先返回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);
      }
    }
  }
}

在這里我調用listing(),其中在獲得響應之后進行jquery ajax調用我返回了對函數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);
});

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM