gpt4 book ai didi

javascript - NodeJS 中变量未读取值

转载 作者:行者123 更新时间:2023-12-02 21:21:19 24 4
gpt4 key购买 nike

我得到的输出为undefined在最后一行代码中。理想情况下,它应该打印 cost 的值我在 call function 的最后一行分配的变量。 cost variable是否正确打印值。我犯了什么错误。或者我如何访问 cost 的值外function .

var request = require("request");
var itemCost;

function call() {

request.get("http://localhost:8080/ords/hr/rest-v3/item/Sugar", (error, response, body) => {

if (error) {
return console.dir(error);
}
let jsonData = JSON.parse(response.body);
let obj = new Object(jsonData);

obj.items.forEach(itemChild => {
let cost = itemChild.itemcost;
console.log(cost);
itemCost = cost; //Assigning value of cost to itemcost. is this correct way?
})

});
}

call();
console.log(itemCost); //here I am getting undefined. I want value of cost here.

最佳答案

因此,request.get异步,您必须在回调中记录itemCost,否则您需要将您的操作与Promise(这里是 example )或其他东西链接起来。

它是未定义的,因为 console.log(itemCost); 实际上并没有等待 request.get 完成,因此 itemCost 是在到达该线之前不会计算。

Basically I have to access that value in some other function. is there any way to do that?

您只需传递 itemCost 变量即可在回调中调用该函数。例如

request.get("http://localhost:8080/ords/hr/rest-v3/item/Sugar", (error, response, body) => {

if (error) {
return console.dir(error);
}
let jsonData = JSON.parse(response.body);
let obj = new Object(jsonData);

obj.items.forEach(itemChild => {
let cost = itemChild.itemcost;
console.log(cost);
itemCost = cost; //Assigning value of cost to itemcost. is this correct way?
})

foo(itemCost); //call the method you need by passing the calculated variable

});
}

关于javascript - NodeJS 中变量未读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60836452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com