[英]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.