如何在继续Javascript Cordova iOS中的循环之前等待回调结果?

问题描述 投票:0回答:1

我有cordova文件插件,我想将图像复制到应用程序的tmp文件夹中,以将其加载到wkwebview中。但是,每当我尝试循环每个图像的复制功能时,循环都不会等待回调处理。该回调仅在循环结束时被调用一次,即,如果我必须显示3张图片,则该函数仅返回一张图片的回调。

//loop
for(var i = 0; i > imagesPath.length; i++){
   getTempPathForImage(imagesPath[i], function(result){
      //display image
   });
}

//the function that gets called
//"/" is the destination i.e root path of tmp directory
function getTempPathForImage(filePath,onSuccess){ 
   moveFile(filePath, "/", function (tempImage) {
      onSuccess(tempImage);
   });
}

我想这样做,以便循环每次都等待回调结果。另外,我无法更改moveFile函数,因为它是cordova文件插件的内置函数,仅适用于回调。

javascript ios cordova ionic-framework callback
1个回答
0
投票

我认为是由于您的循环条件。

应该是

for(var i = 0; i < imagesPath.length; i++){
   getTempPathForImage(imagesPath[i], function(result){
      //display image
   });
}

等待回调,您可以将函数包装到异步中

请参考此链接的示例

https://zellwk.com/blog/async-await-in-loops/

© www.soinside.com 2019 - 2024. All rights reserved.