简体   繁体   English

如何使变量存在于此node.js代码块之外?

[英]How do I get a variable to exist outside of this node.js code block?

I'm new to node.js and I've been trying like hell to wrap my head around how to use it. 我是node.js的新手,我一直在努力尝试如何使用它。 Within this, resp logs just fine with a lot of data. 在此范围内,resp日志可以很好地处理大量数据。 Outside this, mydata is undefined. 除此之外,mydata是未定义的。 I can't figure out why that is, and was hoping someone could help me get the resp data out of the code block. 我不知道为什么,并且希望有人可以帮助我从代码块中获取resp数据。

    var mydata = this.get_json((_servers[i].ip + "/job/" + _servers[i].job + "/lastCompletedBuild/testReport/api/json"), function (resp) {
        console.log(resp);
    });
    console.log(mydata)

Your function is asynchronous. 您的函数是异步的。 That means the this.get_json() call just starts the operation and then your Javascript execution continues. 这意味着this.get_json()调用只是开始操作,然后您的Javascript执行将继续。 Then, sometime LATER when the networking response comes back, it calls the callback function. 然后,稍后在网络响应返回时,它将调用回调函数。

As such, the ONLY place you can use the response is inside the callback. 因此,您可以使用响应的唯一位置是回调内部。 You can call another function from inside the callback and pass it the data, but you cannot use the data in code after your function. 您可以从回调内部调用另一个函数并将其传递给数据,但是您不能在函数后使用代码中的数据。

this.get_json((_servers[i].ip + "/job/" + _servers[i].job + "/lastCompletedBuild/testReport/api/json"), function (resp) {
    // use the response here
    console.log(resp);
    // or call some other function and pass the response
    someOtherFunc(response);
});
// you cannot use the response here because it is not yet available

This is referred to as asynchronous programming and is a core tenet of node.js programming so you must learn how to do it and must adapt your programming style to work this way when using asynchronous operations that return their results via an asynchronous callback. 这被称为异步编程,它是node.js编程的核心宗旨,因此,当您使用通过异步回调返回其结果的异步操作时,您必须学习如何做到这一点,并且必须使您的编程风格适应这种工作方式。 This is definitely different than purely sequential/synchronous programming. 这绝对不同于纯粹的顺序/同步编程。 It is something new to learn when using node.js. 使用node.js时需要学习一些新知识。

There are more advanced tools for programming with asynchronous responses such as promises that are particularly important when trying to coordinate multiple asynchronous operations (sequence them, run them in parallel and know when all are done, propagate errors, etc...). 有许多用于异步响应编程的高级工具,例如诺言,在尝试协调多个异步操作(对它们进行排序,并行运行它们并知道何时完成所有操作,传播错误等)时特别重要。

You may find these related answers useful: 您可能会发现以下相关答案很有用:

Node.JS How to set a variable outside the current scope Node.JS如何在当前范围之外设置变量

Order of execution issue javascript 执行顺序问题javascript

How to capture the 'code' value into a variable? 如何将“代码”值捕获到变量中?

Nodejs Request Return Misbehaving Node.js请求返回行为异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM