1

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ブロック内から関数の戻り値を設定するにはどうすればよいですか?

4

2 に答える 2

4

はい、require 呼び出しが実行され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 に答える