Require.js - 设置回调函数的返回值
Require.js - set return value for callback function
似乎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
块内部为函数设置返回值?
是的,要求调用asynchronously
执行。所以你的例子行不通,因为
function test() {
var returnValue = 'firstValue';
requirejs(['other2'], function(other2) { // <-- ASYNC CALL
other2.doSomething();
returnValue = 'secondValue';
})
return returnValue; // <-- RETURNS FIRST! ('firstValue')
}
在您的示例中,您唯一需要做的就是:
主.js
requirejs.config({
baseUrl: 'js'
});
requirejs(['other1'], function(other1) {
console.log(other1.test())
});
js/other2.js
// No dependencies
define(function() {
return {
doSomething: function() {
return 'secondValue';
}
};
});
JS/其他1.js
// Dependency to other2.js
define(['other2'], function(other2) {
return {
test: function() {
return other2.doSomething();
}
};
});
在此处查看完整示例:http://plnkr.co/edit/hRjX4k?p=preview
看起来
在other1
返回之前,您希望other2
存在,并且您想在other2
上调用一个方法,这将影响您返回的内容other1
。
我想你会想要重新考虑你的依赖关系。 other2
似乎是other1
的依赖;它需要这样定义:
//in other1.js
define('other1', ['other2'], function(other2){
//other2 is now loaded
other2.doSomething();
//return whatever you want for `other1`
});
相关文章:
- 根据是否解析了 Promise 从函数返回值
- 从Ajax函数返回值
- 如何从嵌套的API函数返回值
- 从异步函数返回值
- 我如何才能继续'如果'语句来比较作为参数的多个函数返回值
- 从节点中的回调函数返回值
- 提交时不采用函数返回值.并且没有按预期行事
- 如何从工厂传递的函数返回值
- 为什么在循环中返回时函数返回值未定义
- 从JavaScript中的嵌套函数返回值
- 存在从函数返回值的问题
- 如何从setinterval函数返回值
- javascript:从匿名函数返回值
- angularjs从html调用函数返回值
- 从命名函数返回值
- 无法从Javascript中的嵌套函数返回值
- 这是显示javascript函数返回值的最佳方式吗
- 使用ajax和回调函数向函数传递值/从函数返回值
- 构造函数中的函数返回值
- 尝试从开关语句 -JS- 中的函数返回值