gpt4 book ai didi

javascript - 如何在 RequireJS 模块中进行异步初始化

转载 作者:行者123 更新时间:2023-11-28 07:15:02 25 4
gpt4 key购买 nike

我正在尝试创建一个模块,该模块需要在初始化完成之前从 URL 获取数据。我怀疑我错过了一些明显的东西,但如何让 RequireJS 等到我的异步调用完成后再满足 require 调用。

// data module
(function() {
Papaparse("http://url.csv", {
complete: function(results) {
/* need to return these results from this module after the async call */
}
});

/* what do I return here? */
})

// main
require(["data"], function(d) {
/* displays "undefined" becase the async call is not complete yet */
console.log(d);
})

最佳答案

It's a 6 year old question, but I've needed it before, and may again. I'll answer the general question of asynchronous module initialization:

您需要一个异步加载器插件,例如此处的requirejs-promise:https://github.com/jokeyrhyme/requirejs-promise - 简要转载于此:

define('promise', function(){var g=function(b){return b&&"object"===typeof b?window.Promise&&b instanceof Promise?!0:"function"===typeof b.then:!1};return{load:function(b,h,c){h([b],function(a){var d=function(){c.error.apply(null,arguments)};var e=function(){c.apply(null,arguments)};if(g(a)){var f=a.done||a.then;"function"===typeof a.fail?(f.call(a,e),a.fail(d)):f.call(a,e,d)}else c(a)})}}});

这是一个使用它的快速示例(尽管您通常可能会通过 require 加载插件本身和异步模块):

<!DOCTYPE html>

<html>
<body>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<script>
// Load requirejs-promise.js inline
define('promise', function(){var g=function(b){return b&&"object"===typeof b?window.Promise&&b instanceof Promise?!0:"function"===typeof b.then:!1};return{load:function(b,h,c){h([b],function(a){var d=function(){c.error.apply(null,arguments)};var e=function(){c.apply(null,arguments)};if(g(a)){var f=a.done||a.then;"function"===typeof a.fail?(f.call(a,e),a.fail(d)):f.call(a,e,d)}else c(a)})}}});

// An example async-loading module returning a promise (not
// supported by vanilla requirejs)
define('some-async-module', [], function() {
return new Promise(function(res,rej) {
setTimeout(function() {
var module = { data:[1, 2, 3] };
res(module);
}, 2000);
})
});

// Loading that module with promise! prefix
document.body.innerHTML += 'Loading... 2 sec...<br>';
require(['promise!some-async-module'], function(m) {
document.body.innerHTML += 'Loaded async module: '+JSON.stringify(m);
})
</script>
</html>

关于javascript - 如何在 RequireJS 模块中进行异步初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30931143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com