I was wondering if I use fetch method to return a promise object to handle asynchronous operation inside a function looks like this:
<script>
function test(){
let promise = fetch("https://xxx");
promise.then(()=>{console.log("completed!")});
};
test()
</script>
This will work but my question is once the function test() is executed completely, according to the basic in Javascript where "Function (local) variables are deleted when the function is completed." , my thought is that the promise variable will get deleted and the actual promise object sits somewhere in the memory would have 0 reference, so it would get deleted by javascript. But it still work
Is it the implementation of Promise object sets it work differently in Javascript?
Thank you so much!!
Update 1 : Sorry for my dumb mistake for not declaring promise variable with let or var . Here to add it on. Thanks!
What you have is not a local variable. By declaring promise without a keyword, you have created a global variable attached to the window.
If you use the let or const keyword, you will declare a block-scoped variable, which will be garbage collected at the discretion of the system after its use. (Or even var in this case will scope it to the function)
function test(){
const promise = fetch("https://xxx");
promise.then(()=>{console.log("completed!")});
};
Note the const*
The variables will not be deleted from memory, unless there is no more pointers to the variables. There is a garbage collector in javascript responsible for checking the references and freeing the memory whenever it is possible (You can read more about it here:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management ). So When the functions finished, you cannot access the variable directly, but the memory still remains since there is a pointer to the promise that would change the state of the promise depending on the result of the action (fulfilled or rejected).
This is incorrect code.
Because you did not declare your promise variable to be a local variable of the function, it will becomes an implicit global and will NOT get garbage collected because it's a global.
If you declare it locally with let, const or var in that function (so it is a local variable within that function), then it will be garbage collected when the promise was done and the function was complete.
So, if you do this instead:
<script>
function test(){
const promise = fetch("https://xxx");
promise.then(()=>{console.log("completed!")});
};
test()
</script>
Then, it will be garbage collected when the function and promise are done.
You should explicitly declare ALL variables with let or const in the scope in which you wish to use them. While var still works (for backward compatibility reasons), there are no reasons to use it any more.