function A(){
b()
c()
}
Function c has to be called after function b.
I know there's a concept in JavaScript called callback.
How do I do it in function b?
function b(cb){
//I can't put function c here, because this of c is bound to somewhere and I don't want to mess up.
}
c() will always be called after b() because you placed it there.
The real question is whether or not c() will be called before b() is finished.
If b() is not an async function, then your code is perfect. c() will be called once b() is finished.
function A(){
b(); // *not* async
c();
}
However, if b() is async in nature, you need to provide c() as a callback.
function A(){
b(c); // async
}
function b(cb){
// ...
cb(); // cb() doesn't need "this"
}
Since c() is a bound method, you need to also pass the context (this) to b().
function A(){
/* extract and save context, somehow */
b(c, context); // async
}
function b(cb, context){
// ...
cb.call(context); // cb() doesn't need "this"
}
I don't want to mess up.
If you don't want to play with context passing, you can use a Promise.
function A(){
b().then(function() {
// run "c()" only when "b()" is finished and there were no errors
c();
});
}
function b(){
// ...
// "b()" is *not* async
return Promise.resolve();
}
function b(){
// ...
// "b()" is async
var whenDone = new Promise(function(resolve, reject) {
performAsyncTask(resolve);
})
return whenDone;
}
But wait, there's more.
If you want bleeding edge tech, you can always use async/await
async function A(){
await b(); // VOILA! it's that easy
c();
}
These are the general basic strategies. Of course, you can try to mix-n-match them or try to figure out something new that suits your needs.
You can either use Promises or a callback.
In this case I'd use a callback (as it's a simple use case & promises require crossbrowser checks).
function A() {
b(c); // Pass the function 'c'
}
function c() {
// Do something else
}
function b(callback) {
// Do something
// Run callback
callback(); // This will run whatever method you passed in
}
function b(c){
doSomething();
c();
}
function a(){
b(c);
}
Your understanding is correct. The notion of the callback is when a function is complete. What you're going to have to do is to ensure that the type of input and make sure it is a function and not something different. Take a look at the following example:
function A()
{
alert('I am A function');
b(c);
}
function b(cb)
{
alert('I am "b" function');
/// At the very end, put this code:
if (typeof(cb)==='function')
{
cb();
}
}
function c()
{
alert('I am "c" function');
}
A();
Callbacks in JavaScript are functions that are passed as arguments to other functions. This is a very important feature of asynchronous programming, and it enables the function that receives the callback to call our code when it finishes a long task, while allowing us to continue the execution of the code.
var callback = function() {
console.log("Done!");
}
setTimeout(callback, 5000);
As you can see, setTimeout receives a function as a parameter, this is a callback!
In your case you can do the following:
function b(c) {
c();
}
// calling function b and sending as a parameter an anonymous function
// that will be replaced by the "c" parameter in the "b" function
b(function() {
console.log("inside c");
});
This is almost a closure, just with a little bit more tweaking and you can turn it into one.
Your question is not very clear, let me try to decipher.
If you execute
function A() { b(); c() }
function b() { /* b work */ }
function c() { /* c work */}
Then c will be called after b if by is synchronous.
In the case b is asynchronous, c will be called before b completes.
Then you need indeed a callback as a parameter of b:
function A() { b(c) }
function b(callback) { /* b work */ ; callback() }
function c() { /* c work */ }
Yet in modern js, you'd rather use a promise:
function A() {
b().then( function() {
c()
} )
}
function b() {
return new Promise( function(resolve, reject) {
/* b work */
} )
}
function c() { /* c work */ }
Related
So lets say you have this sync function you call a and another async function b that you want to put within a. And so you would have something like this:
async function b(){
//some code here
}
function a(){
}
And now lets say we add some code into a and call b:
async function b(){
//some code here
}
function a(){
b()
//other code here
}
Now lets say you want to run the code within a only if b has returned its promise. Well if you have direct access to b then its all fine, just make it a sync function. That would work but what if you didn't have access to b. Here comes the problem. If you specifically want to run it after b then you could use something like .then():
async function b(){
//some code here
}
function a(){
b().then(<results for example>=>{
//other code
})
}
But what if a was an async function, how would that work? Could i use await or anything of that sort?
You have to make a function async and await for b function, then b function will return data, otherwise it will return promise.
async function b(){
//some code here
}
async function a(){
const data = await b();
// Do something with data
}
If you have two local functions.
function a() {
alert("a");
}
function c() {
alert("c");
}
a();
and in each local function, lied another local function.
function a() {
alert("a");
b();
function b() {
alert("b");
c();
d();
}
}
function c() {
alert("c");
function d() {
alert("d");
}
}
a();
From what I understand, both functions a and c are "global" as they are first to show up in javascript. local function b is linked to global a and local d to global c, so local function b can read global function c, but are not able to see local function d as that are not global function but local function inside that global function, so it can no longer see and call local function d.
How do you ensure that function of d() can be read by the function of b();
I apologized if this has already been asked, I can't think of the correct keyword to ask, and try to search for the correct keyword does not quite answer my question. I believe the answer has to do with the return, but I never got that to work much less so use it for the function itself.
https://jsfiddle.net/Necrorifter/x1L90pvh/
Unless I am understanding or reading this wrong?
One method is to have each function return the internal functions. Then call them later on.
function a() {
console.log("a");
b();
function b() {
console.log("b");
_c = c();
_c.d();
}
return {b:b}
}
function c() {
console.log("c");
function d() {
console.log("d");
}
return {d:d}
}
a();
//i made ur code smaller cuz seeing it spaced out spaces out my mind
function a() {
alert("a");
function b() {
alert("b");
c();c(1)();//when the parameter is 1, the function d is returned, then i called the returned function(thus i called d)
}b();
}
function c(dd) {
function d() {
alert("d");
}
if(dd==1){return(d);}
alert("c");
}
a();
//there is no built in help for something like this so yea i pulled a workaround
I have a() and a b() inside that a(). I can't make any change to b() but I want to make it unable to call from outside.
So I came up with an idea to save the reference of b() and then set it to null. However, it doesn't work.
Any tips for me?
function a(){
setTimeout(b, 1000);
function b(){
console.log('called');
alert('b called');
}
window.bref = b;
console.log('finish setting');
}
a();
window.bref = null;
console.log('make b() fail to call')
Here is one approach: Enclose the function(s) in a self-executing anonymous function. This is useful so you can cache a flag that determines whether or not b() should run. Then add a static method to a() to toggle this internal flag. The example below runB is such flag. Note that no error is thrown but you can trigger an error if you need to.
(function(parent){
var runB = true;
function b(){
console.log('Executed b()');
}
function a(){
setTimeout(function(){
if(runB) {
b();
} else {
console.log('Skipped b()')
}
}, 500);
console.log('Executed a()');
}
a.disableB = function(){
runB = false;
}
parent.a = a;
})(window);
// Run it normally
a();
// Run it without b()
setTimeout(function(){
a();
a.disableB();
}, 550);
I don't know if this is good practice, but you can wrap window.bref in another function. So here I'm checking if window.bref is a function, if so, call it, or do nothing. The output of this no longer calls b().
function a(){
setTimeout(() => {
typeof window.bref === 'function' ? window.bref() : null;
}, 1000);
function b(){
console.log('called');
}
window.bref = b;
console.log('finish setting');
}
a();
window.bref = null;
console.log('make b() fail to call')
try using let:
function a(){
let b = function(){
console.log('called');
alert('b called');
}
setTimeout(b, 1000);
console.log('finish setting');
}
a();
try{b();}
catch(e){console.log("b is not called")}
I need some concept of threading java script.Actually I struck in one problem .Problem is that
I have one function A () calling function B and C.
function A(){
B();
C();
}
function B(){
//doing some task
i=something;
alert(i);
}
function C(){
// i need value I here.
alert(i) //getting undefined
}
I need to synchronised call ...
How about
function A(){
C(B());
}
function B(){
//doing some task
var i=something;
return i;
}
function C(i){
// i need value I here.
alert(i)
}
or split out for readability
function A(){
var resultFromB = B(); //
C(resultFromB);
}
function B(){
//doing some task
var result=something;
return result; // return it to calling function
}
function C(resultOriginallyFromB) { // passing it
alert(resultOriginallyFromB);
}
Set i as global like,
var i=null;// global i
function A(){
B();
C();
}
function B(){
//doing some task
i=something;
alert(i);
}
function C(){
i need value I here.
alert(i) //getting undefined
}
Read this also
Alternatively, you can use return in B() like,
function A(){
i=B();
C(i);//passing i in C()
}
function B(){
//doing some task
i=something;
alert(i);
return i;//return i
}
function C(i){
// value i has been passed in.
alert(i);
}
Actually it should not really be alerting undefined in function C. As i would have become globally defined already, without the use of var.
Besides try doing it this way, so that you don't clutter the global space:
(function() {
var i;
function A(){
B();
C();
}
function B(){
//doing some task
i=4; // --- or something
alert(i); // --- will alert 4
}
function C(){
// i need value I here.
alert(i) // --- will alert 4
}
A(); // --- Assuming you were calling 'A' earlier as well
})();
And yes, nothing related to threading here.
I have a main function in javascript that is function a() { some code here } and I also have a child function in this main function that looks like
function a() {
function b() {
// some code here
}
}
now I want to call the function b directly. then how to do this.
You can't. You can, however do something like:
function a() {
this.b = function () {
some code here
}
}
And then call it like:
var x = new a();
a.b();
You can also create an object literal with your function:
var a = {
b: function ()
{
//some code here
}
};
And then just say:
a.b();
You could also create a property on the function object itself, and access it that way:
function a()
{
};
a.b = function ()
{
//Some code here
};
And then call it with:
a.b();
You could try explicitly exposing b to the global object like this:
function a() {
function b() {
// some code here
}
window.exposed = b;
}
Don't declare function b inside of function a, just call it like so
function b() {
some code here
}
function a() {
b();
}
There are many solutions here, the only one I think that will suit is to attach the function to the global object so it looks like a declared function. The only difference is that it won't be available until a runs:
function a() {
// Protect against ES5 strict mode, assume function is called as global code
if (typeof this !== undefined) {
this.b = function() { /* whatever */ };
}
}
or perhaps the following suits your coding style better:
function a() {
function b() { /* whatever */};
if (typeof this !== undefined) {
this.b = b;
}
}
Called simply as:
a();
then in ES3 or ES5 non-strict mode, it will work as expected. To overcome ES5 strict limitations where the above will result in a's this being undefined, call a as global code and set its this explicitly:
a.call(this);
or with some other suitable reference to the global object.
I have stayed away from using window since that is less reliable, not least because non–browser hosts will likely not have a window object.