简体   繁体   English

JavaScript 等待内循环

[英]JavaScript await inside loop

I'm trying to read files inside several folders and I need the whole code goes synchronously.我正在尝试读取多个文件夹中的文件,并且我需要整个代码同步进行。

I converted Callback into Promise and try to await it:我将Callback转换为Promise并尝试await它:

function getEntries(reader) {
    return new Promise((resolve, reject) => {
        reader.readEntries((entries) => resolve(entries))
    })
}

async function onDrop(e) {
    e.preventDefault();
    var items = e.dataTransfer.items;
    for (var i=0; i<items.length; i++) {
        
        var entry = items[i].webkitGetAsEntry();
        if (entry.isDirectory) {
            var reader = entry.createReader();
            var entries = await getEntries(reader);
            console.log(entries);
        }
    }
}

But for loop goes just for the first folder.for循环仅适用于第一个文件夹。 What's wrong?怎么了? How I should reorganize my code?我应该如何重组我的代码?

UPDATE更新

The reason the await did not seem to work is due to how browsers handle DataTransfers in the context of async code. await似乎不起作用的原因是浏览器如何在异步代码的上下文中处理 DataTransfers。 See this SO post for details:有关详细信息,请参阅此 SO 帖子:

Here is a jsfiddle that shows the problem clearly:这是一个清楚地显示问题的jsfiddle:

My original answer below is one way to deal handle if you actually wanted an async flow.如果您确实想要异步流,我在下面的原始答案是一种处理方式。

ORIGINAL原来的

I think you meant to say that you want to read directories asynchronously ?我认为您的意思是要异步读取目录? If so...如果是这样...

As it is, the loop will await on each directory.实际上,循环将在每个目录上等待。 Instead, perhaps you want to collect the promises and continue only when all of them have resolved.相反,也许您想收集 Promise 并仅在所有 Promise 都已解决后继续。 Something like:就像是:

function getEntries(reader) {
    return new Promise((resolve, reject) => {
        reader.readEntries((entries) => resolve(entries))
    })
}

async function onDrop(e) {
    e.preventDefault();
    var items = e.dataTransfer.items;
    var promises = [];
    for (var i=0; i<items.length; i++) {
        
        var entry = items[i].webkitGetAsEntry();
        if (entry.isDirectory) {
            var reader = entry.createReader();
            promises.push(getEntries(reader));
        }
    }
    Promise.all(promises).then((entries) => {
     console.log(entries);
    });
}

Try using for-of loop instead of for loop only if you want the previous iteration to complete before moving to next iteration.仅当您希望上一次迭代在移动到下一次迭代之前完成时,才尝试使用 for-of 循环而不是 for 循环。 If that is not important just push every call to getEntries in a promise and await for that promise at end.如果这不重要,只需将每个调用推送到getEntries中的 getEntries 并在最后等待 promise。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM