Cordova resolvaLocalFileSystemUrl()无法在其中进行循环异步 [英] Cordova resolvaLocalFileSystemUrl() cannot async for loop within

查看:215
本文介绍了Cordova resolvaLocalFileSystemUrl()无法在其中进行循环异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的清单[]

$scope.getCategory = function(){
var newList = [];
var list = [ 
{
   Category: 'Souenir',
   Image: 'http://domain.com/souvenir.jpg'
},
{
   Category: 'specialsouvenir',
   Image: 'http://domain.com/specialsouvenir.jpg'
},
{
   Category: 'flower',
   Image: 'http://domain.com/flower.jpg'
},
{
   Category: 'Toy',
   Image: 'http://domain.com/toy.jpg'
}];

for(var i = 0;i < list.length;i++){
        var item = list[i];
        var category = '';
        var image = '';
        var imageName = item.Image.split("/").pop();
        var path = '';
        path = 'cdvfile://localhost/persistent/';
        window.resolveLocalFileSystemURL(path+imageName, function(entry) {
            image = entry.toURL();
             newList.push({Category:item.Category,Image:image});
        });
    }

    return newList;
}

结果显示:

4项[正确]

张图片[正确]

但类别显示最后一个循环项目,而不是每4个项目[错误] 这是iPad的屏幕截图

BUT Category show the last loop item instead in each 4 items [error] Here is the screenshot for iPad

推荐答案

这是一个经典的JS陷阱.由于您是在异步的window.resolveLocalFileSystemURL回调中将项目推送到newList的,因此您只能访问for循环中的最后一个项目,而这是同步的.

It is a classic JS trap. Since you pushing items to newList in window.resolveLocalFileSystemURL callback, which is asynchronous, you have access only to the last item from the for loop, which is synchronous.

因此JS事件循环如下所示: 1代表> 2代表> 3代表> 4代表> 1个回调> 2个回调> 3个回调> 4个回调

So the JS event loop will look something like this: 1 for > 2 for > 3 for > 4 for > 1 callback > 2 callback > 3 callback > 4 callback

有一个很棒的视频对此进行解释.

There is a great video explaining it.

要解决您的问题并为每个项目分配一个唯一的类别,则应将异步操作包装在自调用函数中.这是 jsfiddle 对其进行解释.

To solve your problem and have a unique category for each item, you should wrap async operation in self-called function. Here is jsfiddle explaining it.

这篇关于Cordova resolvaLocalFileSystemUrl()无法在其中进行循环异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆