javascript manipulating values within the scope chain [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've been reading up on Javascript closures and scope chains, but I haven't seen anything about maniuplating variables from within the scope chain. Here's a similar type of scenario I'm running into:
function first() {
var a = [];
a.push({firstFunction: 'yes'});
doSomethingFunction(valueToPassIn, function() {
a.push({secondFunction: 'yes'});
doAnotherThingFunction(newValueToPassIn, function() {
a.push({thirdFunction: 'yes'});
})
})
console.log(a) //returns {firstFunction: 'yes'}
}
how can I get it to return {firstFunction: 'yes', secondFunction: 'yes', thirdFunction: 'yes'}
The code may have syntax errors, but it's the idea I'm trying to understand. I just wrote this code up on the fly so you guys could see a similar scenario as to what I'm trying to fix.
Thanks

I know this was answered in the comments but here is an example of using a callback.
function first(callback) {
var a = [];
a.push({firstFunction: 'yes'});
doSomethingFunction(valueToPassIn, function() {
a.push({secondFunction: 'yes'});
doAnotherThingFunction(newValueToPassIn, function() {
a.push({thirdFunction: 'yes'});
callback(a);
});
});
}
first(function(a){ console.log(a); });
The only problem with this method is that it gets unruly when you have more than 3 or 4 nested callback functions. Promises are the way to handle it.
jsfiddle: http://jsfiddle.net/axqmvdxg/

Related

behavior of javascript 'this' keyword in closure [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
Consider a simple pattern where we call setTimeout within a loop to print the loop counter:
function g(i){
return function()
{
console.log(i);
}
}
for(i=0;i<4;i++)
{
setTimeout(g(i),3000);
}
This returns the expected result:
0
1
2
3
According to my understanding, this function should do the same thing
function f(i){
this.n = i;
return function()
{
console.log(this.n);
}
}
for(i=0;i<4;i++)
{
setTimeout(f(i),3000);
}
Instead, I get varying results, in NodeJS:
undefined
undefined
undefined
undefined
And in Google Chrome:
3
3
3
3
Neither of these results make sense to me, so I was hoping someone else can explain this to me.
You can use an arrow function to keep your this:
function g(i){
return () =>
{
console.log(i);
}
}
for(i=0;i<4;i++)
{
setTimeout(g(i),3000);
}

How to make a line wait for function return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have 2 files
//init.js
var x = getMasterList(location);
console.log(x);
console.log("should have printed list");
And
//read.js
function getMasterList(location) {
var list = [];
ref.child(company).child("listOfLocations").once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
list.push(item);
})
});
console.log("In function");
return list;
}
The console's output is
undefined
should have printed list
In function
The problem is, because of javascript's asynchronous nature, it prints out 'x' before assigning it. I've looked at promises and it doesn't seem like it can help me since it didn't change the async behaviour. I've also looked at callbacks and I can't seem to make them work for multiple files.
Any ways of getting around this so that it only prints after 'x' has a value?
Using callbacks, you can achieve this quite easily.
read.js
function getMasterList(location, callback) {
var list = [];
//do stuff
console.log("In function");
callback(list);
}
init.js
var x = getMasterList(location, function(x){
console.log(x);
console.log("should have printed list");
});

beginner asynchronous value passing and returning in javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Here is the test for the function I am trying to write.
var chai = require('chai');
var doLater = require('../05-callback');
var expect = chai.expect;
describe('05-callback', function () {
it('Can get secret number', function (done) {
doLater(function (secret) {
expect(secret).to.equal(1337);
done();
});
});
});
I have written code that log's a message to the console asynchronously however, this code does not return the 1337 value asynchronously.
function doLater(secret) {
var code = 1337;
(function setImmediate(code) {
console.log("I will be executed immediately");
return code;
})(code);
setTimeout(function secret(code) {
console.log("I will be executed in 2 seconds.");
return code;
}, 2000);
}
Please let me know if this post is not clear and I will edit it. Forgive me if this post is redundant, the simular post's I found were to advanced for me. Thank you for your help!
In order to do what you want to do, you need to use a callback. Example:
function doLater(callback) {
setTimeout(function(){
//after 2 seconds call the callback
return callback(1337);
}, 2000)
}
//pass as param a function that will be called
doLater(function(result) {
console.log(result) //1337
})

Retrieve value from nested functions javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I have had a look, and see some great examples of nesting functions, but even with reading them, I cannot see why I am getting undefined when i call this function:
function readBttnDetec() {
var devid = localStorage.getItem('vBttn');
var bd = 0;
bd = ble.read(devid, 'fffffff0-00f7-4000-b000-000000000000',
'FFFFFFF2-00F7-4000-B000-000000000000',
function(t) {
var data = new Uint8Array(t)
console.log('returns: ' + data[0]); // this returns 6
return data[0];
}, function(f) {
console.log(f);
});
return bd;
}
This is the call:
//check button state
var detecs = readBttnDetec();
console.log(detecs);
if(detecs == 2) {
// fall detection disabled
$('#playfall').removeClass('km-state-active');
} else if(detecs == 6) {
// fall detection enabled
$('#playfall').addClass('km-state-active');
} else {
// error reading button
}
I am missing something simple I am sure of it, but I cannot see it.
Thanks in advance

How to pass parameter in function in modular pattern in javascript [duplicate]

This question already has answers here:
Why is JavaScript's Set Timeout not working? [closed]
(7 answers)
Closed 7 years ago.
Here is my Javascript function;
var searchbox=function(){
var _expandbox=function(count){
};
var _events=function(){
setTimeout(_expandbox,3000);
}
var _init=function(){
_events();
};
return {
init: _init
};
}();
$(document).ready(function(){
searchbox.init();
});
Here the problem is if I call function like setTimeout(_expandbox(4),3000) it won't work.So plese help me how to add parameter in function.
Try wrapping it in an anonymous function:
setTimeout(function() { _expandbox(4); }, 3000);

Categories

Resources