繁体   English   中英

仅 js - 仅运行一次 function

[英]js only - run a function only once

我正在从 firebase 获取一些数据,并且想在第一页加载时仅运行一次 async/await function (以获取数据)。 我已经习惯了 React 和生命周期方法/钩子,但是这个小项目太小了,无法使用 React。 I just need to run this function once, fetch the data, save it to a variable and do not make any further calls to firebase api in the same session.

async function getEntries() {
  const snapshot = await firebase.firestore().collection('riders').get()
  // Do my thing with the data, etc.
  // console.log(snapshot.docs.map(doc => doc.data()));
}

页面加载时是否有任何仅运行此 function 的 js 方式?

是的。 您可以使用自调用(自执行)函数。 语法如下:

(function(){})();

最后的括号用于运行 function。 function 是匿名的。

你可以这样实现它:

(async function () {
    const snapshot = await firebase.firestore().collection('riders').get()
})();

这样你就不能再调用这个 function 并且它只会运行一次。

教程: https://blog.mgechev.com/2012/08/29/self-invoking-functions-in-javascript-or-immediately-invoked-function-expression/

你问的问题在某种程度上重复并在这里回答: JavaScript 中的 Function 只能调用一次

如果您只调用一次 function,您为什么需要 function?

const snapshot = await firebase.firestore().collection('riders').get()
// Do my thing with the data, etc.
// console.log(snapshot.docs.map(doc => doc.data()));

这个顶级等待只在模块中工作,它阻止所有依赖的模块加载。 如果不需要(它们不依赖于数据),或者您不想编写模块,则可以将代码包装在异步 IIFE 中,并将返回的 promise 存储在变量中:

 const dataPromise =  (async function() {
   //...
   return data;
 })();

在加载数据时,您可能希望显示一些加载图标左右。 这可以通过以下钩子轻松完成:

 function usePromise(p) {
   const [state, setState] = useState(null);
   useEffect(() => { p.then(setState); }, []);
   return state;
 }

// Inside a component:
const data = usePromise(dataPromise);
if(data === null)
  return <Loading />;

// show data

我认为您可以在首次加载页面时使用 load 方法加载它,然后将其设置为 cookie 或本地 stroge。 您可以在下一页加载时检查此值。 您可以使用 jQuery 快速完成此操作。

$(window).load(function() {

     var item = localStorage.getItem('test');
     if(item != null){
      // your code
     }
     else {
      localStorage.setItem('test', 1);
     }         
});

您正在寻找的是function结果的记忆。 有几个库可以支持,包括 react。

根据JavaScript:The Good Parts调用一次后,您还可以通过更改 function 实现来使用手工制作的图案

async function getEntries() {
  const snapshot = await firebase.firestore().collection('riders').get()
  // Do my thing with the data, etc.
  // console.log(snapshot.docs.map(doc => doc.data()));
  
  getEntries = async function(){
     return snapshot
  }

  return snapshot
}

最简单的方法是创建一个全局变量,例如:

let isCalled = false;

在 function 体内做:

if(isCalled) return;
//the stuff the function would do
isCalled = true;
//Assign isCalled to true before using a return statement as it will make the program discard the lines below it.

暂无
暂无

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

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