簡體   English   中英

使用Promise等待功能完成

[英]Using promises to wait for function to finish

我已經在線閱讀了一些Promises方法的教程,但仍然有些困惑。 我有一個Node app.js,它執行一些功能,包括連接到數據庫。

 db.connect(function(err) {
     setupServer();
     if(err) {
        logger.raiseAlarmFatal(logger.alarmId.INIT,null,'An error occurred while connecting to db.', err);
        return;
      }

現在,我編寫了一個mocha單元測試套件,該套件封裝了該應用程序並對其執行了多個請求調用。 在某些情況下,發生的情況是測試初始化​​而未確認數據庫已成功連接,即:執行了setupServer()

我將如何對這部分異步代碼實現promises方法,如果沒有實現,我應該使用什么? 我已經嘗試過事件發射器,但這仍然不能滿足所有要求,並且在清除過程中會導致失敗。

您將需要在具有async功能的函數體內使用Promise 對於您的情況,我認為您所說的setupServer()包含ajax請求。

conts setupServer = () => {
  return new Promise((resolve, reject) => {
    //async work
    //get requests and post requests
    if (true)
      resolve(result); //call this when you are sure all work including async has been successfully completed.
    else
      reject(error); //call this when there has been an error
  });
}


setupServer().then(result => {
  //...
  //this will run when promise is resolved
}, error => {
  //...
  //this will run when promise is rejected
});

進一步閱讀:

如果您使用的是Mocha,則應使用異步代碼方法 這樣,您可以指示摩卡咖啡等您調用done功能,然后再繼續進行其他操作。

這將使您開始:

describe('my test', function() {
  before(function(done) {
    db.connect(function(err) {
      setupServer(done);
    });
  })

  it('should do some testing', function() {
     // This test is run AFTER 'before' function has finished
     // i.e. after setupServer has called done function
  });
});

假設您的setupServerdone時調用了done函數:

function setupServer(done) {
  // do what I need to do
  done();
}

暫無
暫無

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

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