2014-11-06 32 views
1
的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) 
    ) 
) 

但是在這種情況下,回覆是立即執行,結果是空的。任何想法我失蹤/做錯了什麼?

+0

如果答覆被parseXML調用,您應該向我們展示該函數的代碼 – 2014-11-06 16:40:13

+0

@RobertLevy reply是一個來自框架並傳遞給我的函數的函數,parseXML來自xml2js – 2014-11-06 16:49:13

回答

0

嘗試使用Q.denodeify。

return Q.denodeify(parseXML)(response); 

您必須將結果承諾返回到then處理函數,以便將結果轉發給由then返回的promise。

0

Acutally,當您創建承諾時,必須解決或拒絕承諾。所以一個promise函數會解決,拒絕回調。

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 
} 

在你的情況下,不要返回響應對象,而是通過解析它將它傳遞給下一個鏈。

+0

您的答案並不是真的有幫助,我不想使用'PROMISE',我必須使用Q庫,'response'是一個XML,我該如何解決它。 – 2014-11-06 17:14:26