简体   繁体   中英

Use parameter in callbacks from function which called it

if i call a function A passing a parameter param, in which an asynchronous function B is called, will the callback C of the asynchronous function B be able to use the parameter param given to function A ? if yes, will this change if in the time between the function B start and the callback C is invoked i re-invoke function A?

Example:

function A(param) {

  value1 = param;
  doc = "hello";
  //this is the async function B;
  database.insert(doc, function() {
    //this is the invoked callback C when the async function is solved. 

    console.log(value1)

    //can i log value1? yes. if yes, will this change if i re-invoke 
    //function A before the callback is invoked or two different processes will start?

  })


}


A('hello');
A('not hello');

Wondering if this, if for the second time A function is invoked before the callback function of the previous invocation, will print the right values on console:

hello; not hello;

and never not hello; not hello;

cause second time's invocation infects first time one.

Yes, the inline callback passed to database.insert() will be able to see the argument passed to function A() . A function has access to any arguments or even local variables in the containing functions.

And, each one will be saved separately so you can call A() as many times as you want and they will each retain separate arguments.

This concept is called a closure, a separate closure is created for each invocation of A() and the closure stays alive as long as any code inside it (including asynchronous callbacks) has not yet completed.

You WILL though need to declare your local variables with var in front of them for them to be truly local variables and unique for each invocation of A() . Without the var , they become implicit global variables and one invocation of A() will mess with the global variables of another invocation of A() . If you do it like this, you are safe:

function A(param) {

  var value1 = param;
  var doc = "hello";
  //this is the async function B;
  database.insert(doc, function() {
    //this is the invoked callback C when the async function is solved. 

    console.log(value1);
    console.log(param);
    console.log(doc);

    //can i log value1? yes. if yes, will this change if i re-invoke 
    //function A before the callback is invoked or two different processes will start?

  })


}


A('hello');
A('not hello');

为了在回调闭包中捕获变量value1 ,您需要将其声明为局部变量:

var value1 = param;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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