I was exploring import/export and stumbled upon this strange behaviour.
It looks like exporting promise function as variable declaration, automagically merges any imports together so it won't re-promise?
Imagine two cases: first:
/* *** fetchMe.js *** */
/ *********************/
var fetchMe = fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(function (data) {
console.log("fromFetch", data);
return data.title
});
export default fetchMe
/* *** a.js *** */
/****************/
import fetchMe from "./fetchMe";
function a () {
console.log("from a");
fetchMe;
}
export default a
/* *** b.js *** */
/****************/
import fetchMe from "./fetchMe";
function b () {
console.log("from b");
fetchMe;
}
export default b
/* *** index.js *** */
/*******************/
import a from "./a";
import b from "./b";
a();
b();
// RESULTS //
// from a
// from b
// fromFetch <--- just once!
second case:
/* *** fetchMe.js *** */
/*********************/
function fetchMe() { // ** <-- DIFFERENCE
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(function (data) {
console.log("fromFetch", data);
return data.title
});
}
export default fetchMe
/* *** a.js *** */
/***************/
import fetchMe from "./fetchMe";
function a () {
console.log("from a");
fetchMe(); // ** <-- DIFFERENCE
}
export default a
/* *** b.js *** */
/***************/
import fetchMe from "./fetchMe";
function b () {
console.log("from b");
fetchMe(); // ** <-- DIFFERENCE
}
export default b
/* *** index.js *** */
/*******************/
import a from "./a";
import b from "./b";
a();
b();
// RESULTS //
// from a
// from b
// fromFetch <--- not once!
// fromFetch <--- twice!?
The only difference between them two is the fragment where the fetchMe is declared as function rather than a variable function.
Is it javascript way of importing a variable only once to save the amount of calls?
Why is calling twice on function call and only once when used as variable?