简体   繁体   English

根据功能的初始化方式,ES6导入的行为有所不同

[英]ES6 import behaves differently based on how function is initialised

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? 看起来像将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. 两者之间的唯一区别是fetchMe被声明为函数而不是变量函数的片段。

Is it javascript way of importing a variable only once to save the amount of calls? 它是只导入一次变量以节省调用次数的javascript方法吗?

Why is calling twice on function call and only once when used as variable? 为什么在函数调用中调用两次,而在用作变量时仅调用一次?

A module is only evaluated once, its exported variables essentially form a singleton. 一个模块仅被评估一次,其导出的变量实际上形成一个单例。 They are shared by all modules that import them. 它们由导入它们的所有模块共享。

In your first example, there is a single promise that is used (well, not really, referenced ) twice. 在您的第一个示例中,有一个使用了两次的诺言(当然,不是真的被引用过 )。
In your second example, there is a single function that is called twice. 在第二个示例中,有一个函数被调用了两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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