【发布时间】:2020-12-02 20:02:17
【问题描述】:
我正在尝试提出一个函数,该函数将目录中的所有歌曲与文件路径、持续时间和上次访问时间一起作为列表提供。虽然循环内的日志确实打印了所需的内容,但响应是在循环完成之前发送的。
observation0:最后的日志发生在循环内的日志之前
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
});
});
我无法在一定程度上理解文档,从而使我能够自己纠正代码:(
感谢您的帮助和建议
【问题讨论】:
-
问题不在于循环与
async/await的组合,它工作得很好,问题是你传递的是普通的旧异步回调而不是使用(和awaiting ) 承诺。
标签: javascript node.js asynchronous async-await fs