尝试将Braintree嵌套的回调转换为NodeJS async / await语法

时间:2019-02-01 09:19:42

标签: javascript node.js async-await braintree

我正在尝试将此Braintree嵌套的回调转换为async / await:

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

我尝试了这种方法,但是得到了undefined响应输出:

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

我在做什么错了?

2 个答案:

答案 0 :(得分:2)

async函数通常不应与未意识到诺言的API配合使用,因为这会导致未链接的诺言失控。

如果gateway.transaction.search不支持诺言,则应予以承诺:

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

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

如果searchResult.customerId().is(braintreeCustomerId)不返回承诺,则无需进行await编辑。

答案 1 :(得分:0)

promise仅会帮助您完成最终的异步结果回调,而不是谓词。

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

这假设transaction.search已经支持诺言。如果没有,您将need to promisify it