2015-07-22 56 views
0

我有這個代碼,我試圖讓它工作,但承諾似乎很混亂,迄今。我已經做了一些研究,並且blubird承諾似乎更加靈活。你們有沒有什麼經驗,並且可能會展示你如何處理這段代碼。如何在這種情況下使用blubird承諾?

下面是代碼:

   var invoicesList; 
       var getInvoices = stripe.getInvoiceList('cus_id', function(err, callback){ 
        if (err) { 
         invoicesList = "An error happened"; 
        }else{ 

         invoicesList = callback.data; 
        }; 
       }); 
    console.log(invoicesList); //Undefined result 

在此先感謝您的問題

+0

呃......哪一個應該是在你的代碼中的承諾? – amenadiel

+0

僅供參考,我在各種條紋文檔中查找名爲'getInvoiceList()'的方法來幫助做出更好的答案,並且找不到有關該方法的任何信息。如果您可以指向該文檔,這將有所幫助。 – jfriend00

+0

可能重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Bergi

回答

2

部分原因是,你不理解的異步響應的意思。這意味着數據將在未來某個時間可用,只有您可以可靠地訪問該數據的位置位於提供結果的回調函數中。您最後的console.log(invoicesList)語句實際上是在調用回調之前執行的。異步回調在未來被稱爲一些不確定的時間。您必須在回調中使用其數據。


這裏的promisifying異步方法,然後使用新的方法來獲得使用承諾的結果的例子:

var Promise = require('bluebird'); 
var getInvoiceList = Promise.promisify(stripe.getInvoiceList); 

getInvoiceList('cus_id').then(function(data) { 
    // you can use the result data here 
    console.log(data); 
}, function(err) { 
    // process an error here 
}); 
// you cannot use the result here because this executes before the 
// async result is actually available 
+0

完美! !謝謝@ jfriend00。現在一個承諾對我來說更有意義,也解決了我的問題。 getInvoiceList實際上調用了一個方法stripe.invoices.list。 – itismelito

相關問題