我正在使用shopify购买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>
答案 0 :(得分:3)
问题正在发生,因为Javascript本质上是异步的。
所有的呼叫都在同一时间执行而不是后果。因为checkoutId, lineItemsToAdd
正在执行时未设置addLineItems
个变量。
您需要使用promises来创建序列。你可以阅读它here。带有promise的代码示例:
<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