有一种方法,使require
电话同步。让它CommonJS的风格:
var module = require('modulepath')
所以,如果你不需要在您需要嵌套调用工厂功能可按,你可以“同步”的要求调用这样......不过既然你做,你都出来了的运气。
AMD风格requre(depsArray, factoryFn)
就像将您的代码推入并行线程一样。没有办法使其“同步”,但可以使用“信号量”来协调结果。
您的问题的答案也很大程度上取决于嵌套的A和嵌套的B消耗。如果他们依靠从上一些产品的要求一样,所以你绝对必须使用“线程信号量”,不能只是把嵌套需要调用到一个名为定义来电:
function someFunction(callback) {
var resultOfOuterCode = someResultOfCalculations
//top level require
require([...], function(...) {
var resultOfTopRequireCode = someOtherResultOfCalculations
var semaphore = {
'count': 2 // represents the number of thread that need to be "done" before
, 'callback':callback // this callback is fired.
, 'checkIfLast': function(){
this.count -= 1
if (!this.count) {
// count is now 0 - time to run our callback
this.callback()
}
}
}
//nested require A
require([...], function(...) {
// using resultOfTopRequireCode // <-- !!!! this is important part
...
semaphore.checkIfLast()
});
//nested require B
require([...], function(...) {
// using resultOfTopRequireCode // <-- !!!! this is important part
semaphore.checkIfLast()
});
});
};
换句话说,只是觉得需要(dependsArray,factoryFn的)作为“线程”,并将您对使用线程的理解应用于它。
你不应该使用依赖关系吗? – epascarello
是的。不过,我们正试图将我们的东西分成不同的文件。例如上面的代码在FileA.js中。 FileB.js用它的回调调用someFunction()。但是它的回调函数依赖于FileA.js的require()回调函数中发生的一些设置。问题在于require的异步性质意味着回调在require()被设置的相关性之前被执行。 – user657352