Reputation: 782
I hava two js file :
//loading.js
define(function () {
function Loading(config) {
}
Loading.prototype.show = function () {
};
Loading.prototype.hide = function () {
};
return function (config) {
return new Loading(config);
};
});
//util.js
define(function () {
var util = {};
util.loading = function (config) {
var result = null;
//I want this code synchronous
require(["loading"],function (Loading) {
result = Loading(config);
});
//there will be result null because of asynchronous
return result;
};
return util;
});
At present,I solve this problem like this:
define(["loading"],function (Loading) {
var util = {};
util.loading = function (config) {
return Loading(config);
};
return util;
});
But I don't like this way.
I want to know requirejs whether to support load js file synchronous.
If not,have a way to solve this problem?
I have seem this question require.js synchronous,feel the answer not solve my problem.
Upvotes: 0
Views: 618
Reputation: 151531
An alternative to your second code snippet is this:
define(function (require) {
var Loading = require("loading");
var util = {};
util.loading = function (config) {
return Loading(config);
};
return util;
});
Note however, that this is still loading the module named "loading" asynchronously even if it looks synchronous.
The thing is that RequireJS in the browser is always loading modules asynchronously. This is true even if it looks synchronous. RequireJS is meant to load modules that conform to the Asynchronous Module Definition (AMD) spec, which is an inherently asynchronous method to load modules. If you want something that looks synchronous and is synchronous you should switch to a module spec that works synchronously.
Upvotes: 1