簡體   English   中英

Promise鏈未在Node.js中執行

[英]Promise chain is not executed in nodejs

我有以下代碼:

Q.fcall(->
    response = req.post({url:url, formData: formData})
    return response
  ).then((response) ->
    reply(response)
  )

它發出請求,然后服務器響應執行reply功能,直到一切正常為止。 響應為XML格式:

<?xml version='1.0' encoding='UTF-8'?>
<foxydata>
    <store_version>2.0</store_version>
    <result>SUCCESS</result>
    <messages>
        <message>Transaction Found</message>
    </messages>
    <transaction>
...
...
...

我想使用節點模塊( xml2js )進行轉換。 所以我做到了:

add = (request, reply) ->

  Q.fcall(->
    response = req.post({url:url, formData: formData})
    return response
  ).then((response) ->
    parseXML(response, (err, result) ->
      reply(result)
    ) 
  )

但是在那種情況下,答復將立即執行,結果為空。 知道我錯過了什么/做錯了什么嗎?

從根本上講,當您創建承諾時,必須將其解決或拒絕。 因此,promise函數將使用resolve,拒絕回調。

dothis
  .then(dothat, error)
  .then(dothattoo)
  .catch(error)

dothis = do(params);

do = function(params) {
  return PROMISE(function(resolve, reject) {
    // use params here as variables
    // do something with params
    if(params) {
      resolve(response)
    } else {
      reject("some error")
    }
  };
}

error = function(err) {
  // handle that err
}

在您的情況下,請勿返回響應對象,而應通過解析將其傳遞到下一個鏈。

嘗試使用Q.denodeify。

return Q.denodeify(parseXML)(response);

您必須將結果諾言返回至then處理函數,以便將結果轉發到then返回的諾言。

暫無
暫無

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

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