1

似乎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块内为函数设置返回值?

4

2 回答 2

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

于 2013-11-07T21:33:47.683 回答
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`
});
于 2013-11-07T21:20:58.427 回答