使用extend关键字防止函数在异步调用完成之前返回
Prevent function to return before async call is finished using the extend keyword
代码就是这样的。
//Extending a Nativescript module.
var test = ImageProvider.extend({
getImage: function(url){
//async call to get the image from cache
cacheService.getImage(url,
function(image){
return image
},
function(error){
return null
});
}
});
如何防止在提供图像之前返回getImage函数?我不喜欢用打字稿或babel来解决这个问题。但如果需要,请提供建议。(也试过babel,打字没有任何运气)我尝试通过设置使用等待和让步:
"android": {"v8Flags": "--expose_gc --use_strict --harmony"}
在package.json文件中没有成功。
使用成品给出误差的样本
"use strict"
function onNavigationgTo(args){
yield test();
}
function* test(){
return 1;
}
在我添加yield关键字之前,它可以正常工作。使用收益率得出以下结果。SyntaxError:意外的严格模式保留字File:"unknown"
您想要做的可能不是一个好主意,因为它会在程序加载时阻塞UI。这个问题通常通过回调或promise/自定义任务实现来解决。回调示例:
getImage: function(url, callback){
//async call to get the image from cache
cacheService.getImage(url,
function(image){
callback({ image: image, error: null });
},
function(error){
callback({ image: null, error: error });
});
}
然后使用情况将看起来像
ImageProvider.getImage('someurl.png', function(result) {
if (result.image) {
// image has successfully downloaded -- good!
}
else {
// handle result.error
}
});
为此使用ES6 Promises。
var test = ImageProvider.extend({
getImage: function(url){
//async call to get the image from cache
return new Promise(function(resolve, reject) {
cacheService.getImage(url,
function(image){
resolve(image);
},
function(error){
reject(error);
});
});
}
});
然后像这个一样使用
test.getImage('http://...').then(function(image) {
// do stuff
});
所有主流浏览器都支持本机承诺。。IE除外(边缘支持)。如果你想要更广泛的浏览器支持,我建议你使用bluebird。
相关文章:
- 如何从ajax调用返回.wrap()元素
- Ajax调用返回当前html页面,而不是请求的文件
- 如何在模式框中显示ajax调用返回的数据
- AngularJS$http.post调用返回502(坏网关)错误
- 有没有更好的方法可以测量从Ajax调用返回数据所需的总时间
- 格式化AJax调用返回的Json,并将其分配给javascript变量
- calling.trigger(“click”),它在ajax调用返回的javascript代码中
- 在异步调用返回之前隐藏页面
- 对php文件的Ajax调用返回该文件中的JS代码,而不是执行它
- 如何在下一次 AJAX 调用中访问从一个 AJAX 调用返回的变量
- jQuery 延迟的 AJAX 调用返回值
- Django Ajax 调用返回 403 错误请求
- 从异步调用返回数组,然后为数组的每个元素返回其他异步调用
- 从函数返回函数而不调用返回的函数
- 当Json Length过长时,对ASP.NET MVC Controller的Ajax调用返回404
- 如何从jQuery中Ajax调用返回的数据中获取对象
- 如果statusCode不是200,那么从http调用返回什么类型的错误对象
- 如何使用jsonp调用返回的数据在Durandal中呈现视图
- 为什么我的ajax调用返回null
- 如何获取ajax调用返回的元素数