簡體   English   中英

調用Promise鏈后調用Q Promise函數

[英]Call a Q promise function after promise chain invoked

我正在使用帶有Q Promise庫的Node.js應用程序。 我有兩組承諾鏈,一組用於控制流程,另一組用於調用從中檢索數據的服務方法。我的問題是,我需要將承諾鏈的返回值傳遞給我的其他承諾鏈。

MyExample.js

bookService.getBookById(bookId)
  .then(bookDetals)
  .then(function(returnValue) { // <- (A)
    res.send(200, returnValue); // <- (C)
    return returnValue;
  }).catch(function(error) {
    logger.error('Error getting values');
    res.send(500, error);
  });


bookDetals = function(book) {
  myService.retrieveATypeData(book, bookId)
    .then(function(bookData) {
      myService.retrieveBTypeData(bookId)
        .then(function(bdata) {
          bookData[bTypeData] = bdata;
          myService.retrieveCTypeData(bookId)
            .then(function(cdata) {
              bookData[cTypeData] = cdata;
            }).done(function() {
              return bookData; // <- (B)
            })
        });
    });
};

在上面的代碼中,我正在調用bookService.getBookById(bookId)並獲取書。 然后我調用bookProtals函數,這是一個承諾鏈。 但是我的問題是,在諾言鏈結束之前,它會返回returnValue 我如何獲得承諾鏈的返回值(在行(B)中)以返回到位(C)。 目前它返回之前。 因此,在C語言中,它表示未定義。

由於您正在使用Node,因此我將轉向ES6 Promises。 如果您當前的版本尚不支持ES6 Promises,建議您切換到為您多填充的庫( es6-promise )。 使用ES6,您可以執行以下操作:

// mock async promise
const getThing = id => (
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({
        id
      });
    }, 250);
  })
);

// mock async promise
const getDetailsA = thing => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(Object.assign({}, thing, {
        a: 'purple'
      }));
    }, 250);
  })
};

// mock async promise
const getDetailsB = thing => (
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(Object.assign({}, thing, {
        b: 'monkey'
      }));
    }, 250);
  })
);

// mock async promise
const getDetailsC = thing => (
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(Object.assign({}, thing, {
        c: 'dishwasher'
      }));
    }, 250);
  })
);

getThing('123')
  .then(getDetailsA)
  .then(getDetailsB)
  .then(getDetailsC)
  .then(console.log)
  .catch(console.error);

您需要返回一個承諾

bookDetals = function(book) {
  return Q.Promise(function(resolve, reject, notify) {
    myService.retrieveATypeData(book, bookId)
        .then(function(bookData) {
          myService.retrieveBTypeData(bookId)
            .then(function(bdata) {
              bookData[bTypeData] = bdata;
              myService.retrieveCTypeData(bookId)
                .then(function(cdata) {
                  bookData[cTypeData] = cdata;
                }).done(function() {
                  resolve(bookData); // <- (B)
                })
            });
        });
  }  
}


編輯

deferred此處討論的反模式。 老實說,它可能是最好使用填充工具 ,因為承諾是在ES6規范。

暫無
暫無

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

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