0

I have this code which that i am trying to make it work but the promises seem very confusing so far. I have done some research and the blubird promises seem to be more flexible. Do you guys have any experience and maybe show a case how you would deal with this code.

Here is the code:

                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

Thanks in advance

itismelito
  • 245
  • 3
  • 11
  • uh... which one is supposed to be a promise in your code? – ffflabs Jul 22 '15 at 00:06
  • FYI, I looked in various stripe documentation for a method called `getInvoiceList()` to help in making a better answer and could not find any info on that method. If you can point to that doc, it would help. – jfriend00 Jul 22 '15 at 00:12
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Bergi Jul 22 '15 at 00:38

1 Answers1

2

Part of your issue is that you were not understanding what an asynchronous response means. It means that the data will be available sometime in the future and the ONLY place you can reliably access that data is inside the callback function that delivers the result. You last console.log(invoicesList) statement is actually executing BEFORE the callback has been called. Async callbacks are called some indeterminate time in the future. You must consume their data inside the callback.


Here's an example of promisifying an async method and then using that new method to get a result using promises:

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
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Perfect!!! Thank you @jfriend00. Now a promise makes more sense for me and also fixed my issue. The getInvoiceList is calling a method stripe.invoices.list actually. – itismelito Jul 22 '15 at 00:24