I am trying to implement a shopify api in node and want to call the post requests synchronously since i want to retrieve the product id after posting and store it in an array. I am making use of a library called deasync as a synchronous waiting loop. The script used to work before and suddenly stopped working. When i log my calls without the deasync loop, i see that responses are returned from shopify, however, when I'm running my script with the deasync loop, my identifier stays null, and the deasync loop keeps iterating. I am relatively new to asynchronous requests in node.js. The scope of my identifier variable seems correct. The only thing I can imagine for now is that the callback happens in a parallel node.js universe that is seperate from my while loop. Any help would be much appreciated, thx!
function postProduct(Store, product, variants) {
var identifier = null;
var post_data = {
"product": product
};
Shopify.post('/admin/products.json', post_data, function(err, data, headers) {
identifier = {
id: data.product.id,
price: data.product.price,
variants: variants
};
});
while(identifier === null) {
require('deasync').runLoopOnce();
}
return identifier;
}
All of this deasync
solutions can't to be stable, because they are depend on internal engine implementation.
Just try to learn async way. It's really simple.
Simplified example with native Promise
:
var products = [
{Store: {}, product: {}, variant: {}},
{Store: {}, product: {}, variant: {}},
];
Promise.all(products.map(postProduct)).then(function(identifiers){
// use identifiers
});
function postProduct(data) {
return new Promise(function(ok, fail){
Shopify.post(...., function(){
//...
ok(identifier);
});
});
}