Callback Function Using Variables Calculated Outside of It

Callback function using variables calculated outside of it

You can use the use keyword to inherit variables from the parent scope. In your example, you could do the following:

$callback = function($val) use ($avg) { return $val < $avg; };

For more information, see the manual page on anonymous functions.

If you're running PHP 7.4 or later, arrow functions can be used. Arrow functions are an alternative, more concise way of defining anonymous functions, which automatically capture outside variables, eliminating the need for use:

$callback = fn($val) => $val < $avg;

Given how concise arrow functions are, you can reasonably write them directly within the array_filter call:

return array_filter($arr, fn($val) => $val < $avg);

Access variables from within the callback function of the 'each' function

You should use the use keyword to use it in the anonymous scope
http://php.net/manual/en/functions.anonymous.php

$example = function () use ($message) {
var_dump($message);
};

$example();

How to get a variable value outside a callback function NodeJS

You can do something like this.

const question = () => {
return new Promise((resolve, reject) => {
readline.question('Insert preposition ', (prep) => {
readline.close();
resolve(prep)
})
})
}

async function iniciar() {
let my_prep = await question();
console.log('OK',my_prep);
return true;
}

await keyword waits on the promise to resolve, so you need to return promise. Also the use of async/await and promises is to avoid callback hell.

Using variable outside of ajax callback function

The code you have provided is perfectly valid -- and, in fact, icon does "maintain" it's value. The problem, likely, is that get() runs asynchronously -- only calling the anonymous function after 'data.xml' has been fully loaded from the server. So the real-world sequence of execution looks something like this:

  1. call get('data.xml', function(xml){...}) (starts loading data.xml)
  2. call console.log(icon) (icon is still null at this point)
  3. (data.xml finished loading) now the anonymous function is called, which assigns the value to icon: icon = xml.documentElement.getElementsByTagName("icon").

If you want to do something with the value of icon, after the 'data.xml' has been fetched, then you'll need to do it inside the anonymous callback function. Like this:

var icon; 
$(function(){

$.get('data.xml', function(xml){
icon = xml.documentElement.getElementsByTagName("icon");
console.log(icon);
});
});

good luck!


Note: you can still use icon from code that is outside the anonymous function, but you'll need to wait to access it, until after the anonymous function has been run. The best way to do this is to put the dependent code into its own function, and then call that function from within the callback function:

var icon; 
$(function(){

$.get('data.xml', function(xml){
icon = xml.documentElement.getElementsByTagName("icon");
loadIcon();
});

function loadIcon() {
console.log(icon);
// ... do whatever you need to do with icon here
}
});

Variable outside of callback in NodeJS

What you're asking for is synchronous (or blocking) execution, and that's really contrary to the design and spirit of node.js.

Node, like JavaScript, is single-threaded. If you have blocking code, then the whole process is stopped.

This means you have to use callbacks for anything that will take a long time (like querying from a database). If you're writing a command-line tool that runs through in one pass, you may be willing to live with the blocking. But if you're writing any kind of responsive application (like a web site), then blocking is murder.

So it's possible that someone could give you an answer on how to make this a blocking, synchronous call. If so, and if you implement it, you're doing it wrong. You may as well use a multi-threaded scripting language like Ruby or Python.

Writing callbacks isn't so bad, but it requires some thought about architecture and packaging in ways that are probably unfamiliar for people unaccustomed to the style.

How to extract the value of a variable outside Nodejs callback function

function doCall(urlString) {    return new Promise((resolve, reject) => {        request.get(            urlString,            null,            null,            (err, data, result) => {                if (error) reject(error);                var statusCode = result.statusCode;                resolve(data);            });    });}
async function myBackEndLogic() { try { const result = await doCall(urlString); console.log(result); //return JSON.parse(result) if you want
} catch (error) { console.error('ERROR:'); console.error(error); }}
myBackEndLogic();

Why are my variables undefined outside of the callback function?

You declared those variables outside of the scope that you're using them. To fix your code, declare them outside of the function:

var uid1 = "";
var accessToken2 = "";
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
uid1 = response.authResponse.userID;
alert(uid1);
accessToken2 = response.authResponse.accessToken;
alert(accessToken2);
} else if (response.status === 'not_authorized') {

} else {

}

alert(uid1); // Values will be set here.
alert(accessToken2);
});
alert(uid1); // Values won't reliably be set here.
alert(accessToken2);

Update: As suggested by the comments below, because your getLoginStatus method is asynchronous, you will likely not have values when you call the alert() outside the method. I have added additional alerts inside the call back to show where you should try to access the values.

Using a Variable Out of Scope of a Callback Function in Node.js / Express.js

Not directly, but there are a couple of options to get closer to that.

One would be to have your callback be a defined function and use that as the callback:

const doSomething = (err, res) => { /* do something */ }

geocoder.geocode('abc', doSomething);

Not really much different, but can make it a little cleaner.

You can also "promisify" the function to have it return a Promise. Something like this would do the trick:

const geocodePromise = (path) => new Promise((resolve, reject) => {
geocoder.geocode(path, (err, res) => err ? reject(err) : resolve(res));
});

geocodePromise('abc')
.then(res => { /* do something */ })
.catch(err => { /* do something */ });

Finally, if you are using Babel for transpiling (or Node version 7.6.0 or higher, which has it natively), you can use async and await. Using the same promisified version of the function as above, you'd have to wrap your main code in an async function. I generally use a self-calling anonymous function for that:

(async () => {
try {
const res = await geocodePromise(path);

/* do something with res */
} catch (err) {
/* do something with err */
}
})();

With this, you get the closest to what you want, but you'll still have to wrap your main code up in a function because you can't await at the top level.



Related Topics



Leave a reply



Submit