nodejs return 到主函数

nodejs return to main function

I.m nodejs 的新手,遇到一些问题,returning 主要功能的价值。

我尝试过这样的事情,但对我的工作不起作用。

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;

}

我需要 return 从请求到主函数的正文值 request_price

编辑:

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 函数显示 console.log 正常,但对象 OfferData console.log return 未定义价格

你试过的方法不对。

你尝试做的是调用 request_price() 并且在内部你正在进行 request 调用(如果你使用 request library 则应该是 request.get(...) );

request() 函数异步运行,因此可能需要一段时间才能解决,但代码不会等待,因此它会前进到 return price;,它还没有值。

request() 函数的响应返回时,request_price() 函数已经完成 运行 所以这就是它不起作用的原因。

为了让它工作,您需要在 request() 函数回调中处理您的 price

你可以看看我写的这个建议,它可能是 (IMO) 一个更清晰的实现:

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);

进一步编辑:

在您刚刚添加的情况下,您需要遵循以下逻辑:

  1. 更改 responseHandler 函数,使其可以执行 OfferData.items.push()
  2. 使用循环调用 request_price() 任意多次
  3. inventory[j] 对象作为参数传递给 request_price() 函数
  4. 当响应返回并由 responseHandler 处理时,从 responseHandler 内部调用 OfferData.items.push() 因为现在 priceinventory[j] 都是可用