在 javascript 中加载远程数据、缓存和继续
基本用例。我有一个全局变量,用于存储远程拉取的数据。如果没有数据,那么我想首先加载它,等待它加载,然后继续处理。如果没有必要的话,我真的不想使用同步进程。
考虑这样的事情,其中 _companies 是一个全局变量......
if (_companies === undefined || _companies.length == 0) {
loadExternalData();
}
// do something with the data in _companies
我觉得我错过了一些明显的东西。我知道我可以调用 async = false 但这似乎很麻烦。我还可以将块中的所有代码放在一个函数中,创建一个 if..else,然后从 loadExternalData() 以及我的 else 语句中调用该函数,但这似乎又很麻烦。看起来我应该能够将整个事情包装在回调中,但我不知道该怎么做。
Basic use case. I have a global variable where I store remotely pulled data. If there is no data then I want to load it initially, wait for it load, and then continue processing. I don't really want to use a synchronous process if I don't have to.
Consider something like this where _companies is a global variable...
if (_companies === undefined || _companies.length == 0) {
loadExternalData();
}
// do something with the data in _companies
I feel like I'm missing something obvious. I understand that I can call async = false but that seems like a cludge. I could also put all the code in the block in a function, make an if..else and then call the function from loadExternalData() as well as in my else statement but again that seems like a cludge. It seems like I should be able to wrap that entire thing in a callback but I don't know how to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看一下下面的代码,包括注释。该代码与您问题中的函数具有相同的结构。如果有任何不清楚的地方,请添加评论。
另请参阅:MDN:使用 XMLHttpRequest
Have a look at the code below, including the comments. The code has the same structure as the functions in your question. If anything is unclear, add a comment.
See also: MDN: Using XMLHttpRequest