Shopify Buy SDK — 添加行项目错误

Shopify Buy SDK — Add line items error

我正在使用 shopify buy SDK 创建自定义店面:

shopify.checkout.create().then((checkout) => {
  checkoutId = checkout.id
  console.log('checkout id: ' + checkoutId) // Works OK
})

shopify.product.fetchAll().then((products) => {
  lineItemsToAdd = [
    {variantId: products[0].variants[0].id, quantity: 1}
  ]
  console.log('line items to add: ' + lineItemsToAdd) // Works OK
})

shopify.checkout.addLineItems(checkoutId, lineItemsToAdd).then((checkout) => {
  console.log('checkout line items: ' + checkout.lineItems)
}) // Throws error

我得到的错误是:

index.js?7327:3705 Uncaught (in promise) TypeError: Cannot read property 'checkoutLineItemsAdd' of undefined
at eval (index.js?7327:3705)
at <anonymous>

出现此问题是因为 Javascript 本质上是异步的。

您的所有调用同时执行,而不是结果。因为 checkoutId, lineItemsToAdd 变量在 addLineItems 执行时没有设置。

您需要使用 promises 来创建序列。你可以阅读它 here。带有承诺的代码示例:

<script>

const client = ShopifyBuy.buildClient({
  domain: '-----------------------',
  storefrontAccessToken: '--------'
});
var checkoutPromise = client.checkout.create()
var productPromise = client.product.fetchAll()


Promise.all([checkoutPromise,productPromise]).then(([checkout,products]) => 
{
    var lineItemsToAdd = [
        {variantId: products[0].variants[0].id, quantity: 1}
      ]
    var checkoutId = checkout.id

    console.log('checkout id: ' + checkoutId)       
    console.log('line items to add: ' + lineItemsToAdd)

    client.checkout.addLineItems(checkoutId, lineItemsToAdd).then((checkout) => {
        console.log('checkout line items: ' + checkout.lineItems)
    })
})
</script>

P.S。上面的代码是 not supported in IE