【问题标题】:How to wait for callback result before continuing the loop in Javascript Cordova iOS?如何在 Javascript Cordova iOS 中继续循环之前等待回调结果?
【发布时间】:2020-05-19 01:45:41
【问题描述】:

我有 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】:

    我认为这是因为你的循环条件。

    应该是

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

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

    示例请参考此链接

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 2015-12-22
      相关资源
      最近更新 更多