返回在函数中异步获取的值

Return a value asynchronously acquired in a function

本文关键字:获取 异步 函数 返回      更新时间:2023-09-26

这可以被认为是一个一般的编程问题,甚至是逻辑问题,因为它与语言无关。

我在JavaScript中有以下代码:

...
{text: 'Modelo', dataIndex: 'model', filterable: true,
    renderer: function(value) {
        // this will asynchronously load the object "Model" from the database which have primary key equals to "value".
        MyApp.model.Model.load(value, {
            scope: this,
            success: function(record, operation) {
                // this will be executed if succeeded. I need to return the "record" parameter in the outer function.
            }
        });
        return value; // There must be a way to return the "record" parameter from above.
    }
}, 
...

如评论中所述,有一个外部函数renderer调用一个内部异步函数load,该函数检索我需要从外部函数返回的值record

我尝试了一些丑陋的东西,比如一个空的while循环,等待在外部函数中声明的变量在内部函数中设置,然后返回它,但没有成功,循环最终是无限的。

您不能直接返回,因为在返回发生后success回调触发。相反,你可以在你的代码中继续这个回调模式…如果您更改renderer的函数签名以接受回调:

{text: 'Modelo', dataIndex: 'model', filterable: true,
    renderer: function(value, successCb) {    
        MyApp.model.Model.load(value, {
            scope: this,
            success: function(record, operation) {
                if(successCb){
                    successCb(record, operation);
                }
            }
        });
        //return void, and communicate back to the caller using successCb above.
    }
}, 

renderer的调用者提供一个回调:

myObj.renderer(someVal,function(rec,op){
    //do something
});

现在你可以从你的函数中异步获取数据