Require.js - 设置回调函数的返回值

时间:2013-11-07 21:13:49

标签: javascript callback requirejs

似乎require调用是异步执行的,允许程序流继续执行。当我尝试将require调用中的值集用作返回值时,这会出现问题。例如:

main.js:

$(document).ready(function() {
    requirejs.config({
        baseUrl: 'js'
    });

    requirejs(['other1'], function(other1) {
        console.log(other1.test()); //logs out 'firstValue', where I would expect 'secondValue'
    }
});

other1.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块内设置函数的返回值?

2 个答案:

答案 0 :(得分:4)

是的,需要执行调用asynchronously。所以你的例子不起作用,因为

function test() {
    var returnValue = 'firstValue'; 
    requirejs(['other2'], function(other2) { // <-- ASYNC CALL
        other2.doSomething();
        returnValue = 'secondValue'; 
    })

    return returnValue; // <-- RETURNS FIRST! ('firstValue')
}

您的示例中唯一需要做的是:

<强> main.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 / other1.js

// Dependency to other2.js
define(['other2'], function(other2) {
   return {
     test: function() {
        return other2.doSomething();
     }
   };
});

请参阅此处的完整示例:http://plnkr.co/edit/hRjX4k?p=preview

答案 1 :(得分:1)

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`
});