Passing variable in parent scope to callback function

前端 未结 3 1382
忘掉有多难
忘掉有多难 2020-11-30 15:32

This is more of a JavaScript Closure question than a Firebase question. In the following code, the Firebase callback isn\'t recognizing the variable myArr in the parent scop

3条回答
  •  心在旅途
    2020-11-30 15:34

    The child_added event is not immediately executed, therefore is not synchronous and you can't rely on it to have executed, before the log call at the end of your function.

    The procedure is:

    • Define myArr
    • Instantiate Firebase
    • Assign event handler for child_added
    • Log the value of myArr
    • Return myArr - end of function
    • Now at some point after this, the child_added event is fired, which pushes to your array, but as you can see, your show_fb() function has already finished executing by this point.

提交回复
热议问题