0
我找不出正确的方法来做到这一点:正确的方法或方法如果条件设置在循环内吗?
我打电话给产品的外部API,我得到一个响应我想将这些产品添加到我的数据库,如果响应包含next_page url循环再次,直到没有剩下next_page
这里是我想出了:
var products = api.ProductsActive('GET', {includes: 'Images', limit: 1});
requestProducts = function(){
products.results.forEach(function(product){
var sameproduct = apiProducts.findOne({listing_id: product.listing_id});
if (sameproduct) {
console.log('found sameproduct');
return;
}
//Add userId to current product so we can assosicate products belong to "X" user
var productExtend = _.extend(product, {userId: Meteor.userId()});
apiProducts.insert(productExtend);
});
//If there is next page get the next page number and get products
var nextPage = products.pagination.next_page;
if (nextPage !== null) {
products = api.ProductsActive('GET', {includes: 'Images', page: nextPage, limit: 1});
console.log(products);
}
};
//loop at least once, and then if more pages found
do {
requestProducts();
}
while (products.pagination.next_page !== null);
往往根本没有工作的权利,我不知道这是否是这样的功能我正确的方法真的帮助你的输入!请帮我找出正确的方法!
是的,你是正确的它与回调是流星我有回调选择的选项或者不是,我已经创建了API原型,所以我现在一定会找出一些东西,非常感谢让我知道我应该使用回调来重复这个动作,我不确定如何处理这个,这是有道理的,我将研究并阅读和阅读更多关于回调,以清楚和代码的东西:) – zumbamusic 2014-12-19 13:57:24
其实我的服务器端代码是同步的,但来自客户端的调用是异步的,所以我想出了这个代码似乎工作,你可以评论就是这样罚款或是这是一个黑客,我完全错了我刚刚读回调的一切:)? http://pastebin.com/bahTa50G – zumbamusic 2014-12-19 21:20:55
@zumbamusic只要'api.ProductsActive'允许同步结果就可以。我不确定这是哪个API,但如果它使用光纤为Meteor设计,那么你很好。如果它是一个普通的nodejs api,你可以使用'Meteor.wrapAsync'(http://docs.meteor.com/#/full/meteor_wrapasync)进行同步。你需要小心你为每一个使用光纤,这样你就可以在每个光纤环境中使用Meteor代码。 – Akshat 2014-12-20 09:48:17