似乎require
调用是异步执行的,允许程序流程围绕它们继续进行。当我尝试将require
调用中设置的值用作返回值时,这是有问题的。例如:
主.js:
$(document).ready(function() {
requirejs.config({
baseUrl: 'js'
});
requirejs(['other1'], function(other1) {
console.log(other1.test()); //logs out 'firstValue', where I would expect 'secondValue'
}
});
其他1.js
function test() {
var returnValue = 'firstValue'; //this is what is actually returned, despite the reassignment below...
requirejs(['other2'], function(other2) {
other2.doSomething();
returnValue = 'secondValue'; //this is what I really want returned
})
return returnValue;
}
if(typeof module != 'undefined') {
module.exports.test = test;
}
if(typeof define != 'undefined') {
define({
'test':test
});
}
如何从require
块内为函数设置返回值?