首页 > 解决方案 > 如何在节点 js 中正确使用等待/异步与 for 循环

问题描述

我试图想出一个函数,将目录中的所有歌曲作为列表提供,以及文件路径、持续时间和上次访问时间。虽然循环内的日志确实打印了所需的内容,但响应是在循环完成之前发送的。

观察0:最后的日志发生在循环内的日志之前

router.get('/', function (req, res) {

    let collection = new Array();

    // glob returns an array 'results' containg the path of every subdirectory and file in the given location
    glob("D:\\Music" + "/**/*", async (err, results) => {

        // Filter out the required files and prepare them to be served in the required format by
        for (let i = 0; i < results.length; i++) {
            if (results[i].match(".mp3$") || results[i].match(".ogg$") || results[i].match(".wav$")) {

                // To get the alst accessed time of the file: stat.atime
                fs.stat(results[i], async (err, stat) => {
                    if (!err) {

                        // To get the duration if that mp3 song
                        duration(results[i], async (err, length) => {
                            if (!err) {
                                let minutes = Math.floor(length / 60)
                                let remainingSeconds = Math.floor(length) - minutes * 60

                                // The format to be served
                                let file = new Object()
                                file.key = results[i]
                                file.duration = String(minutes) + ' : ' + String(remainingSeconds)
                                file.lastListend = moment(stat.atime).fromNow()

                                collection.push(file)
                                console.log(collection) //this does log every iteration
                            }
                        })
                    }
                })
            }
        }
        console.log(collection); //logs an empty array
    })

    res.json({
        allSnongs: collection
    });
});

我无法在一定程度上理解文档,使我能够自己纠正代码:(

我感谢您的任何帮助和建议

标签: javascriptnode.jsasynchronousasync-awaitfs

解决方案


此答案不会修复您的代码,而只是为了消除任何误解:

fs.stat(path, callback); // fs.stat is always asynchronous.
                         // callback is not (normally), 
                         // but callback will run sometime in the future.

await像 fs.stat 这样使用回调而不是 Promise的函数的唯一方法是自己做出 Promise。

function promiseStat( path ){
    return new Promise( ( resolve, reject ) => {
        fs.stat( path, ( err, stat ) => {
            if( err ) reject( err );
            else resolve( stat );
        };
    });
 }

现在我们可以:

const stat = await promiseStat( path );

推荐阅读