javascript - 如何在节点 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
});
});
我无法在一定程度上理解文档,使我能够自己纠正代码:(
我感谢您的任何帮助和建议
解决方案
此答案不会修复您的代码,而只是为了消除任何误解:
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 );
推荐阅读
- logstash - Elastic Stack CSV 年份列
- android - 如何在用户根据要求输入数据的 android studio 中创建动态 Imageview
- titanium - 合金编译器失败但经典的钛作品
- java - 使用 Java Apache POI 搜索特定的 Excel 单元格
- javascript - while() 循环无限期地运行;条件不会改变;.replace() 没有按预期工作
- flutter - Flutter 中的 Streams 和 Sockets 有什么区别?
- mysql - 项目同时使用 MySQL 和 PostgreSQL 时从 JsonStringType 切换到 JsonBinaryType
- javascript - 从字符串中删除给定值以及 Javascript 中的逗号
- python - 如何在 ModelForm 中添加密码占位符?
- r - 将具有累积分布的辅助轴添加到ggplot R