Re: [w3c/payment-request] Retrying a payment (#705)

Ok, `.retry()` with recursive validation with event support (my submission for JS1k this year?): 

```JS
async function doPaymentRequest() {
  const request = new PaymentRequest(methodData, details, options);
  const response = await request.show();
  await recursiveValidate(response);
  await response.complete("success");
}

async function recursiveValidate(response) {
  const promisesToFixThings = [];
  const errors = await validate(response);
  if (!errors) {
    return;
  }
  if (errors.shippingAddressErrors) {
    const promise = fixField(response, "shippingaddresschange", shippingValidator);
    promisesToFixThings.push(promise);
  }
  if (errors.payerErrors) {
    const promise = fixField(response, "payerdetailschange", payerValidator);
    promisesToFixThings.push(promise);
  }
  await Promise.all([response.retry(errors), ...promisesToFixThings]);
  await recursiveValidate(response);
}

function fixField(response, event, validator) {
  return new Promise(resolve => {
    // Browser keeps calling this until promise resolves.
    response.addEventListener(event, async function handler(ev) {
      const promiseToValidate = validator(response);
      ev.updateWith(promiseToValidate);
      const errors = await promiseToValidate;
      if (!errors) { // yay! fixed!
        event.removeEventListener(event, handler);
        resolve();
      }
    });
  });
}

doPaymentRequest();
```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/payment-request/issues/705#issuecomment-386161086

Received on Thursday, 3 May 2018 00:26:48 UTC