簡體   English   中英

發送響應后如何在node.js api中運行后台任務?

[英]How to run background task in node.js api after sending response?

我有一個要求,我必須在返回 api 的響應后運行一分鍾的后台進程。 該后台進程將對 mongodb 進行一些操作。

我的方法是,我在返回響應后為后台進程發出一個事件。

這個操作有什么最好的方法嗎? 請幫我。

謝謝,

您可以使用 EventEmitter 來觸發后台任務。

或者您可以在返回響應之前觸發異步任務。

我會實現某種簡單的內存隊列。 在返回響應之前,我會向隊列中添加一個任務,發出一個事件告訴聽眾隊列中有任務。

編輯:

我不確定我是否完全理解您的用例。 但這可能是一種方法。

如果您沒有執行 mongo 的參考,您可能必須進行一些快速查找或創建,然后返回響應,然后運行任務

const myqueue = []

const eventHandler = new EventEmitter();

eventHandler.on('performBackgroundTask', () => {

  myqueue.forEach(task => {
    // perform task
  })

})

app.get('/api', function (req, res) {

    const identificationForItemInMongo = 123

    myqueue.push(identificationForItemInMongo)

    eventHandler.emit('performBackgroundTask',     identificationForItemInMongo)

   res.send('Send the response')
})

當你想對 db 進行異步調用並等待結果時,你需要在 ES6 中使用回調或使用 promises 或 async/await。

閱讀此以獲取更多信息

您可以為您的方法使用 Promise 鏈。 調用第一個 Api,一旦收到響應,就會在 UI 中顯示值,然后第二個調用將自動停止,並且不會干擾任何 UI 進程。 您可以在此處參考有關承諾鏈的更多詳細信息。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

var promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

//Run the background process.
var promise2 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "Success!"
  return promise2;
}).then(function(value){
  // Response for the second process completion.
}).catch(function(){
  // Failure for first api call/ second api call
});

暫無
暫無

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

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