0

I am trying to convert this Braintree nested callback into async/await:

  var stream = gateway.transaction.search(function (search) {
    search.customerId().is(braintreeCustomerId);
  }, function (err, response) {
    response.each(function (err, transaction) {
      console.log(transaction);
    });
  });

I tried this approach but I am getting undefined response output:

  await gateway.transaction.search(async (search) => {
    const response = await search.customerId().is(braintreeCustomerId);
    console.log(response)
  })

What am I doing wrong?

James
  • 3,597
  • 11
  • 41
  • 76

2 Answers2

2

async functions shouldn't be generally used with APIs that are unaware of promise because this results in runaway promises that aren't chained.

If gateway.transaction.search doesn't support promises, it needs to be promisified:

const search = util.promisify(gateway.transaction.search).bind(gateway.transaction);

const searchResult = await search();
const response = searchResult.customerId().is(braintreeCustomerId);

If searchResult.customerId().is(braintreeCustomerId) doesn't return a promise, it doesn't need to be awaited.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

The promise will only help you with the final asynchronous result callback, not the predicate.

const response = await gateway.transaction.search(function (search) {
  search.customerId().is(braintreeCustomerId);
});
response.each(function (err, transaction) {
  console.log(transaction);
});

This assumes that transaction.search already supports promises. If not, you will need to promisify it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375