访问回调中声明的返回变量

时间:2015-12-16 17:28:29

标签: javascript jquery requirejs

因此,我将通过说我对回调函数的理解是有限的,因此我有可能在回调函数或RequireJS中犯了一个初学者错误。

基本上,我正在寻找的是能够从API访问方法的值,并通过循环回调函数中包含的内容来创建变量。然后我想获取该变量并在RequireJS define语句的返回部分返回其值。下面是我想要做的简化示例。

//call an api library then loop through to get all values for your object
define(['apiLibrary'], function (api) {
    //create var that contains api method of current object
    var apiMethod = api.someMethod();
    //declare value var to be used inside callback
    var value ='';
    //call otherMethod, specifying an arguement and use callback to access contents of method
    apiMethod.otherMethod('arg',function (reply) {
        //loop through each value inside callback
        $.each(reply.item, function (key, value) {
            //add values to variable for each instance of method
            value += 'the key is '+key+' and the value is'+value;
        });
    });
    //return some values as well as the value set above for the overall define method
    return {
        valueFromElsewhere: 'hardcoded for example',
        valueFromLibrary: value //value is '' since it is set insde a callback function
    }
});

我感谢您提前获得的任何帮助!谢谢!

编辑: 关于promises的信息非常有用,并且肯定有助于我总体上围绕异步函数,但我需要在RequireJS return语句中返回我的变量数据。有一个下游程序,我无法控制,期望以我的define函数的返回值提供的特定格式返回数据。

1 个答案:

答案 0 :(得分:1)

您需要异步访问该值。一个很好的处理方式是承诺:

var getValue = new Promise(function(resolve, reject) {
    apiMethod.otherMethod('arg',function (reply) {
        $.each(reply.item, function (key, value) {
            value += 'the key is '+key+' and the value is'+value;
        });
        resolve(value);
    });
});
return {
    valueFromElsewhere: 'hardcoded for example',
    getValueFromLibrary: getValue
};

然后,您可以使用.then api:

访问它
foo.getValueFromLibrary.then(function(value) {
    console.log('Value:', value);
});