This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 4 years ago.
What is the use of 'cb => cb(snapshot)' ?
if (this._snapshotCallbacks.length > 0) {
const snapshot = gl.canvas.toDataURL();
this._snapshotCallbacks.forEach(cb => cb(snapshot));
this._snapshotCallbacks = [];
}
requestSnapshot (callback) {
this._snapshotCallbacks.push(callback);
}
this._snapshotCallbacks.forEach(cb => cb(snapshot));
can be rewritten as
this._snapshotCallbacks.forEach(function (callback) {
callback(snapshot)
});
i think it's clear when there is no arrow function?
this._snapshotCallbacks.forEach(cb => cb(snapshot));
means there is a collection of callbacks and the code here invokes them one after each other.
forEach is a function that exists on the array prototype that will take a function as a parameter and invoke this function for each element in the collection. When the function is invoked, the element is passed as the sole argument to the function that forEach took cb => cb(snapshot) is an es6 shorthand function definition.
So in your example, cb is a callback thats then invoked with the snapshot.
Basically, this is the same idea in a forloop
var function1 = (msg) => { alert(msg);}
var function2 = (msg) => { alert(msg.toUpperCase());}
var functions = [function1, function2];
for(var i = 0; i < functions.length; i++){
var fnToApply = functions[i];
fnToApply("hello world");
}
in which an array of functions is invoked in a loop, and each function is designed ahead of time to know what it takes as a param
Related
This question already has answers here:
In ES6, what happens to the arguments in the first call to an iterator's `next` method?
(3 answers)
Closed 6 months ago.
Consider this generator function.
Why is the argument of the first call to .next() essentially lost? It will yield and log each of the letter strings but skips "A". Can someone offer an explanation. Please advise on a way that I can access each argument each argument of the .next() method and store it in an array within the generator function?
function* gen(arg) {
let argumentsPassedIn = [];
while (true) {
console.log(argumentsPassedIn);
arg = yield arg;
argumentsPassedIn.push(arg);
}
}
const g = gen();
g.next("A"); // ??
g.next("B");
g.next("C");
g.next("D");
g.next("E");
This is a limitation of generator functions. If you really want to be able to use the first argument, you can construct your own iterator manually.
const gen = () => {
const argumentsPassedIn = [];
const makeObj = () => ({
done: false,
value: undefined,
next: (arg) => {
argumentsPassedIn.push(arg);
console.log(argumentsPassedIn);
return makeObj();
},
});
return makeObj();
}
const g = gen();
g.next("A");
g.next("B");
g.next("C");
g.next("D");
g.next("E");
As per the docs
The first call of next executes from the start of the function until the first yield statement
So when you call the first next, it just calls the generator function from start to till the first yield and then returns and from next call it works normal.
To make you code work, you should try like this.
function* gen(arg) {
let argumentsPassedIn = [];
while (true) {
console.log(argumentsPassedIn);
arg = yield arg;
argumentsPassedIn.push(arg);
}
}
const g = gen();
g.next()
g.next("A"); // ??
g.next("B");
g.next("C");
g.next("D");
g.next("E");
The parameter passed to the first call to .next() is ignored as of ES2022. This is because the first call to .next() runs the function until the first yield or return is encountered and the following calls will make yield operator return the value passed as a parameter. This is usually solved by calling .next() unconditionally after calling the generator function.
There is, however, a stage 2 proposal that aims to solve this problem by introducing new syntax to get the value passed to the .next() method that most recently resumed execution of the generator.
This question already has answers here:
stop settimeout in recursive function
(7 answers)
Javascript delete a function
(3 answers)
Closed 2 years ago.
const resumeInfinity = () => {
window.speechSynthesis.resume();
const timeoutResumeInfinity = setTimeout(resumeInfinity, 1000);
console.log(timeoutResumeInfinity);
}
utterThis.onstart = () => {
resumeInfinity();
};
need the (resumeInfinity) function to stop working after the speechSynthesi
To avoid error messages that resumeInfinity is not a function you shouldn't delete it but set it to an empty function. But as you set defined resumeInfinity as const you can't change that function.
So what you can do is to either change it to:
let resumeInfinity = () => {
// ... your code
}
And then do change it later to an empty function resumeInfinity = () => {}
But you need to keep in mind that if that original function was passed as callback earlier to somewhere else (e.g. like here setTimeout(resumeInfinity, 1000)) that this callback will still refer to the old function.
So a better solution would be to check if the function should still valid to be executed and do an early out otherwise.
const resumeInfinity = () => {
if( /* some check if isn't valid to call that function anymore */ ) {
return
}
window.speechSynthesis.resume();
const timeoutResumeInfinity = setTimeout(resumeInfinity, 1000);
console.log(timeoutResumeInfinity);
}
But all of these above solutions are in fact just a workaround, because if the logic of your application is correct then such a situation should never happen. So the need to do something like this indicates that you more likely need to think about restructuring your code.
If it is just about stopping the timeout then you need to call clearTimeout(timeoutResumeInfinity), and make timeoutResumeInfinity available at the place at which you know that the speechSynthesi finished.
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 years ago.
I would like to pass an argument to a callback function inside a for loop. The problem is the callback is called after the for loop ends and then the parameter does not exist anymore.
See the following code snippet:
function foo(x){
console.log(x)
}
for(var i = 0; i < arr.length; i++) {
var myObj = customObject()
myObj.on('click', function(){
foo(arr[i])
}
}
myObj is clicked on after the for loop ends which triggers an error:
TypeError: arr[i] is undefined
Is there any way to force the argument to be passed by its value at time of binding the callback function?
Try an IIFE:
myObj.on('click', function() {
(e => foo(e))(arr[i]);
});
The problem was that the click event was firing after the whole loop had finished - so i was arr.length, had not passed the conditional statement in the loop, and as such arr[i] was undefined.
You'd also need to use let instead:
for (let i = 0; i < arr.length; i++) {
let myObj = createObject();
myObj.on("click", function() {
(e => foo(e))(arr[i]);
});
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
How I can return a string from a javascript callback
I have two functions, main function is working on loaded.
and another function is used to calling web service.
I would like to know how can JS return the string value to main function.
thanks
function thisCallJSON(webServiceURL) {
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(webServiceURL, function(response)
{
if(response.data && response.text)
{
var jsondata = response.data;
for (var key in jsondata)
{
var value = jsondata[key];
//alert("Member Name : "+value["memNm"]);
}
}
else
{
//alert("Member Name : Not Found !");
}
}, params);
}; function main(){
var txt_string = "";
txt_string = thisCallJSON("http://192.100.1.59");
}
You can assign the value to the variable in the scope of the main function, but it won't happen before the main function is finished executing because of the event loop. Instead, you should put your code inside the callback, or better yet, look at how you would use javascript promises to accomplish this.
This question already has answers here:
What do multiple arrow functions mean in JavaScript?
(7 answers)
Closed 6 years ago.
Can anyone explain what the code is doing here
return () => next => action => {
const callAPI = action[CALL_API];
if (typeof callAPI === 'undefined') {
return next(action);
}
let { endpoint } = callAPI;
const { types, bailout } = callAPI;
It is initially returning a function but I don't get why there are two further fat arrows after the first.
If the arrow function has only one parameter, then the parameter around that is optional. You just need to have enough parenthesis to understand them better.
return () => (next) => (action) => {
it returns a function, which when invoked returns another function which accepts one parameter, next. Now when that function is invoked, it returns another function, which accepts another parameter action.
That code can be rewritten like below,
return function() {
return function(next) {
return function(action) {
It seems that the outer function returns a function with parameter next and that returns another one function with parameter action. That code in the link that you given has not minified, but that seems to be obfuscated.