简体   繁体   中英

How to know when an operation has finished - Callback?

I'd like to know when an operation has finished - It's an iteration where we don't know the size of the list be iterated over (it could be any length.)

Here's my code:

var array = [];

stripe.charges.list().autoPagingEach(function(charge) {

  var post  = {
    chargeId: charge.id,
    customerId: charge.customer,
    sourceId:charge.source.id,
    amount:(charge.amount/100).toFixed(2),
    description:charge.description,
    dateAndTime:moment(charge.created*1000).format('YYYY-MM-DD HH:mm:ss'),
    chargeStatus:charge.status,
    failureMessage:charge.failure_message
  };

  array.push(post)

});

How can I console.log(array.length) once the iteration has finished?

I have seen some examples that use a callback with Done() which would appear to be what I'm after - But I can't figure how to factor it into this code.

As per Stripe's documentation, stripe.charges.list() returns an object with the list of charges in the data property.

You can do:

let charges = stripe.charges.list();
let pending_charges = charges.data.length;

charges.autoPagingEach(function(charge) {
    // do your thing

    pending_charges -= 1;
    if ( pending_charges == 0 ) {
        // call a function after the last charge has been processed
        // and be careful with failing autoPagingEach() executions
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM