简体   繁体   English

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

[英]How to wait for callback result before continuing the loop in Javascript Cordova iOS?

I have the cordova file plugin and i want to copy images to tmp folder of the app to load it into the wkwebview.我有cordova文件插件,我想将图像复制到应用程序的tmp文件夹以将其加载到wkwebview中。 But whenever i try to loop the copy function for each image, the loop does not wait for the callback to process.但是每当我尝试为每个图像循环复制函数时,循环不会等待回调处理。 The callback only gets called once at the end of the loop ie if i have to display 3 images, the function only returns callback for one image.回调只在循环结束时被调用一次,即如果我必须显示 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);
   });
}

I want to make it so that the loop waits each time for the callback result.我想让循环每次等待回调结果。 Also, i cant change the moveFile function because it is a built-in function of cordova file plugin that works only with callbacks.此外,我无法更改 moveFile 函数,因为它是cordova 文件插件的内置函数,仅适用于回调。

I think it's because of your loop condition.我认为这是因为你的循环条件。

it should be它应该是

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

to wait for the callback you can wrap your function into async等待回调,你可以将你的函数包装成异步

Please refer to this link for an example请参阅此链接以获取示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Javascript JQuery中,如何在继续循环之前等待模式在for循环中关闭? - In Javascript JQuery, how to wait for a modal to close in a for loop before continuing? 在继续 for 循环之前等待 HTTP 请求中的回调 function 完成 - Wait for completion of callback function in HTTP request before continuing with for loop Javascript / jQuery make函数在继续之前等待回调 - Javascript / jQuery make function wait for callback before continuing 如何在继续之前等待 cordova.plugins.sqlitePorter.exportDbToSql 完成? - How to wait cordova.plugins.sqlitePorter.exportDbToSql to complete before continuing? 在继续之前等待循环完成 - Wait for for loop to complete before continuing 在继续执行之前,如何等待javascript承诺返回值? - How to wait for javascript promise to return value before continuing execution? 如何让程序在继续使用javascript之前等待if语句完成? - How to make the program wait for the if statement to finish before continuing in javascript? 在继续循环之前获得回调完成? - getting a callback to finish before continuing a loop? Selenium - 在继续之前等待Javascript函数执行 - Selenium - Wait for Javascript function to execute before continuing 等待函数完成,然后再继续使用JavaScript - Wait for a function to finish before continuing in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM