返回在函数中异步获取的值
Return a value asynchronously acquired in a function
这可以被认为是一个一般的编程问题,甚至是逻辑问题,因为它与语言无关。
我在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
});
现在你可以从你的函数中异步获取数据
相关文章:
- 如何从SeleniumWebdriver获取异步Javascript响应
- 异步获取数据使用JavaScript同步获取数据
- 无法使用开放天气图 API 异步获取天气
- 从异步回调中获取值
- 如何处理异步获取的数据
- 在我的案例中,如何获取异步数据
- 从 Ajax 获取由 ZombieJS 的异步点击事件触发的 Http 错误
- 在呈现“页面”之前异步获取数据
- 如何通过连接多个异步javascript调用,从对象数组中排序并获取第一个obejct
- 在Ember.js中异步从DB获取
- backbone.js视图没有't由于异步获取而显示结果;t渲染
- 异步编程-如何在对象数组中循环,并使用从api获取的数据更改每个对象的属性
- NodeJS异步模块:如何在回调中获取results对象
- 从 Android 中的 url 获取异步加载的 html(通过 ajax)
- JavascriptKango:如何在非异步函数中获取异步JS函数的返回
- 获取异步父函数的参数
- 如何获取异步JSONP请求的值
- 如何在流星函数中获取异步数据
- 美元AngularJS http.获取异步执行顺序
- 使用Jquery获取异步加载svg元素的id