Reputation: 500
I.m newbie in nodejs and have some problem , with returning value to main function.
i try something like this but dosent work for my.
function request_price(name)
{
var price;
(function(price_r) {
request('http://jack.dev/price.php?name='+encodeURIComponent(name), function(error, response, body)
{
console.log(body);
price_r = body;
});
})(price);
return price;
}
I need return body value from request to main function request_price
Edit:
for (var i = 0; i < offer.items_to_receive.length; i++) {
for (var j = 0; j < inventory.length; j++) {
if (offer.items_to_receive[i].assetid == inventory[j].id) {
var price = request_price(inventory[j].market_name, responseHandler);
OfferData.items.push({
id: inventory[j].id,
name: inventory[j].name,
image: inventory[j].icon_url,
price: price
});
break;
}
}
}
setTimeout(function () {
console.log(OfferData);
}, 1000)
responseHandler function showing console.log fine , but object OfferData on console.log return undefined on price
Upvotes: 0
Views: 1610
Reputation: 1117
It doesn't work the way you tried it.
What you try to do is to call a request_price()
and inside you are making a request
call (which should be request.get(...)
if you are using the request library );
The request()
function runs asynchronously so it might take a while until it's resolved, but the code doesn't wait so it moves forward to return price;
which doesn't have a value yet.
By the time the response from the request()
function comes back, the request_price()
function has already finished running so this is the reason why it's not working.
In order to make it work, you need to process your price
in the request()
function callback.
You can have a look at this suggestion that I wrote which might be (IMO) a cleaner implementation:
var request = require('request');
function request_price(name, responseHandler) {
var price;
request.get('http://jack.dev/price.php?name='+encodeURIComponent(name), responseHandler );
}
function responseHandler(error, response, body) {
console.log(body);
var x = ... //process body
return x;
}
request_price('bob', responseHandler);
Further edit:
In this case you've just added, you need to follow this logic:
responseHandler
function so it can perform the OfferData.items.push()
request_price()
as many times as you likeinventory[j]
object to the request_price()
function as an argumentresponseHandler
, call OfferData.items.push()
from the inside of responseHandler
because now both price
and inventory[j]
are availableUpvotes: 1