小编典典

有没有办法可以同步获取条带中的订单项

javascript

我有这个功能

async function getLineItems(session_id) {
    var lineItems = []
    await stripe.checkout.sessions.listLineItems(
        `${session_id}`,
        function(err, data) { // this function is called asynchronously, but I need it synchronous
            lineItems = data.data
        }
    )

    return lineItems // this is called before i get the data
}

而且我需要以某种方式使该功能stripe.checkout.sessions.listLineItems同步。或者lineItems在调用函数后以某种方式返回。现在该函数每次都返回一个空数组。


阅读 174

收藏
2022-07-25

共1个答案

小编典典

使用await关键字时,您可以将已履行承诺的返回值分配给变量,如下所示:

async function getLineItems(session_id) {
  try{
    const lineItems = await stripe.checkout.sessions.listLineItems(`${session_id}`)
    return lineItems.data;
  } catch(e){
    //handle error
  }
}

由于listLineItems是分页 API,我强烈建议使用自动分页来收集所有 lineItems

async function getLineItems(session_id) {
  try{
    const lineItems = [];
    for await (const lineItem of stripe.checkout.sessions.listLineItems(`${session_id}`)) {
      lineItems.push(lineItem);
    }
    return lineItems;
  } catch(e){
    //handle error
  }
}
2022-07-25