【发布时间】:2016-11-01 16:54:28
【问题描述】:
在 node.js 中发出 get 请求时,我在尝试从数组返回索引值时遇到问题。这是使用 shopify 模块,但我相信这将适用于所有获取请求。 我的功能是:
ShopifyObj.Shopify.get('/admin/products.json', function(err, data, headers){
console.log(data.products[0]);
});
以上返回:
"console.log(data.products[0]);
TypeError:无法读取未定义的属性“0”
然而;当我尝试在没有索引的情况下使用 console.log 时,我得到一个数组:
ShopifyObj.Shopify.get('/admin/products.json', function(err, data, headers){
console.log(data.products);
});
//returns
[ { id: 6560603013,
title: 'Dog',
body_html: 'A cute dog',
vendor: 'Test store 1994 1994',
product_type: '',
created_at: '2016-10-27T11:11:32-04:00',
handle: 'dog',
updated_at: '2016-10-27T11:11:33-04:00',
published_at: '2016-10-27T11:11:00-04:00',
template_suffix: null,
published_scope: 'global',
tags: '',
variants: [ [Object] ],
options: [ [Object] ],
images: [ [Object] ],
image:
{ id: 16395126725,
product_id: 6560603013,
position: 1,
created_at: '2016-10-27T11:11:33-04:00',
updated_at: '2016-10-27T11:11:33-04:00',
src: 'https://cdn.shopify.com/s/files/1/1569/4167/products/imagejpeg_0_5.jpg?v=1477581093',
variant_ids: [] } },
{ id: 6560596805,
title: 'Long sleeve tshirt',
body_html: 'Super long sleeves',
vendor: 'Test store 1994 1994',
product_type: '',
created_at: '2016-10-27T11:10:45-04:00',
handle: 'long-sleeve-tshirt',
updated_at: '2016-10-27T11:13:56-04:00',
published_at: '2016-10-27T11:10:00-04:00',
template_suffix: null,
published_scope: 'global',
tags: 'dog, short-sleeve-t-shirt',
variants: [ [Object] ],
options: [ [Object] ],
images: [ [Object] ],
image:
{ id: 16395113157,
product_id: 6560596805,
position: 1,
created_at: '2016-10-27T11:10:47-04:00',
updated_at: '2016-10-27T11:10:47-04:00',
src: 'https://cdn.shopify.com/s/files/1/1569/4167/products/profilepic.jpg?v=1477581047',
variant_ids: [] } },
{ id: 6560275461,
title: 'Short Sleeve T-Shirt',
body_html: 'A nice t-shirt',
vendor: 'Test store 1994 1994',
product_type: '',
created_at: '2016-10-27T10:38:58-04:00',
handle: 'short-sleeve-t-shirt',
updated_at: '2016-10-27T10:38:59-04:00',
published_at: '2016-10-27T10:38:00-04:00',
template_suffix: null,
published_scope: 'global',
tags: '',
variants: [ [Object] ],
options: [ [Object] ],
images: [ [Object] ],
image:
{ id: 16394553413,
product_id: 6560275461,
position: 1,
created_at: '2016-10-27T10:38:59-04:00',
updated_at: '2016-10-27T10:38:59-04:00',
src: 'https://cdn.shopify.com/s/files/1/1569/4167/products/World-Wide-Web.jpg?v=1477579139',
variant_ids: [] } } ]
我觉得我在异步方面做错了什么,但我无法弄清楚。当 console.log 的 settimeout() 几秒钟后,它将正确显示。有没有什么方法可以得到我想要的结果,而不必在任意时间内使用 settimeout?
【问题讨论】:
标签: javascript node.js shopify