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

Require.js - set return value for callback function

本文关键字:函数 返回值 回调 设置 js Require      更新时间:2023-09-26

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