Poc*_*chi 8 javascript asynchronous
我有以下代码在循环中运行:
var index = fileNames[x].lastIndexOf("/") + 1;
var currentImageName = fileNames[x].substr(index);
if (currentImageName.indexOf(".jpg") != -1) {
reader.getFileAsBlob(fileNames[x])
.done(function(blob) {
picturesFilePathArray.push({
fileName: currentImageName,
fileURL: blobURL(blob)
});
refreshKMZList();
});
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我试图将具有2个属性的对象保存到数组中.该对象应具有标识符和结果.(分别是fileName和fileURL).但由于此函数是异步的(通过promise执行).到"getFileAsBlob"完成时,currentImageName已经更新,最终以我的许多具有相同标识符的对象结束(最后一个在完成之前处理).
这可能是一个非常容易的问题,但我对javascript很新,还没有找到任何关于它的东西.
我认为解决方案可能是将变量传递给"done"函数,但我认为这个函数是方法返回的函数,并且已经设置好了.(我不知道它看起来如何)
编辑:
代码就在普通循环中
for (x = 0; x<fileNames.length; x++)
Run Code Online (Sandbox Code Playgroud)
因此创建一个函数,以便无法更改变量
function getFile (filmName, imageName) {
reader.getFileAsBlob(fileName)
.done(function(blob) {
picturesFilePathArray.push({
fileName: imageName,
fileURL: blobURL(blob)
});
refreshKMZList();
});
}
Run Code Online (Sandbox Code Playgroud)
并称之为
if (currentImageName.indexOf(".jpg") != -1) {
getFile (fileNames[x], currentImageName);
}
Run Code Online (Sandbox Code Playgroud)
或者你可以做类似的事情
if (currentImageName.indexOf(".jpg") != -1) {
(function (fileName, imageName) {
reader.getFileAsBlob(fileName)
.done(function(blob) {
picturesFilePathArray.push({
fileName: imageName,
fileURL: blobURL(blob)
});
refreshKMZList();
});
})(fileNames[x], currentImageName);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13845 次 |
最近记录: |