如何在节点 js 中正确使用 await/async 和 for 循环
How to properly use await/async with for loops in node js
我正在尝试想出一个函数,将目录中的所有歌曲作为列表提供,以及文件路径、持续时间和上次访问时间。虽然循环内的日志确实打印了所需的内容,但响应是在循环完成之前发送的。
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
});
});
我对文档的理解程度无法让我自己更正代码:(
感谢您的帮助和建议
此答案不会修复您的代码,只是为了消除任何误解:
fs.stat(path, callback); // fs.stat is always asynchronous.
// callback is not (normally),
// but callback will run sometime in the future.
await
使用回调而不是承诺的 fs.stat 功能的唯一方法是自己做出承诺。
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 );
有足够的时间来研究您的代码。
我会这样写的,我做了很多改变。并且有效
srv.get('/', async function (req, res) {
// glob returns an array 'results' containg the path of every subdirectory and file in the given location
let results = await new Promise((res, rej) =>
glob("D:\Music" + "/**/*", (err, results) => {
if (err != null) rej(err);
else res(results);
})
);
// Filter out the required files and prepare them to be served in the required format by
results = results.filter(
(result) =>
/\.mp3$/.test(result) ||
/\.ogg$/.test(result) ||
/\.wav$/.test(result)
);
const collection = await Promise.all(
results.map(async (result) => {
const stat = await new Promise((res, rej) =>
fs.stat(result, (err, stat) => {
if (err != null) rej(err);
else res(stat);
})
);
const length = await new Promise((res, rej) =>
duration(result, (err, length) => {
if (err != null) rej(err);
else res(length);
})
);
const minutes = Math.floor(length / 60);
const remainingSeconds = Math.floor(length) - minutes * 60;
// The format to be served
return {
key: result,
duration: `${minutes} : ${remainingSeconds}`,
lastListend: moment(stat.atime).fromNow(),
};
})
);
console.log(collection);
res.json({
allSnongs: collection,
});
});
给予,
[
{
key: 'D:\Music.mp3',
duration: '0 : 27',
lastListend: 'a few seconds ago'
},
{
key: 'D:\Music.mp3',
duration: '0 : 27',
lastListend: 'a few seconds ago'
},
{
key: 'D:\Music.mp3',
duration: '0 : 52',
lastListend: 'a few seconds ago'
},
{
key: 'D:\Music.mp3',
duration: '2 : 12',
lastListend: 'a few seconds ago'
}
]
我正在尝试想出一个函数,将目录中的所有歌曲作为列表提供,以及文件路径、持续时间和上次访问时间。虽然循环内的日志确实打印了所需的内容,但响应是在循环完成之前发送的。
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
});
});
我对文档的理解程度无法让我自己更正代码:(
感谢您的帮助和建议
此答案不会修复您的代码,只是为了消除任何误解:
fs.stat(path, callback); // fs.stat is always asynchronous.
// callback is not (normally),
// but callback will run sometime in the future.
await
使用回调而不是承诺的 fs.stat 功能的唯一方法是自己做出承诺。
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 );
有足够的时间来研究您的代码。
我会这样写的,我做了很多改变。并且有效
srv.get('/', async function (req, res) {
// glob returns an array 'results' containg the path of every subdirectory and file in the given location
let results = await new Promise((res, rej) =>
glob("D:\Music" + "/**/*", (err, results) => {
if (err != null) rej(err);
else res(results);
})
);
// Filter out the required files and prepare them to be served in the required format by
results = results.filter(
(result) =>
/\.mp3$/.test(result) ||
/\.ogg$/.test(result) ||
/\.wav$/.test(result)
);
const collection = await Promise.all(
results.map(async (result) => {
const stat = await new Promise((res, rej) =>
fs.stat(result, (err, stat) => {
if (err != null) rej(err);
else res(stat);
})
);
const length = await new Promise((res, rej) =>
duration(result, (err, length) => {
if (err != null) rej(err);
else res(length);
})
);
const minutes = Math.floor(length / 60);
const remainingSeconds = Math.floor(length) - minutes * 60;
// The format to be served
return {
key: result,
duration: `${minutes} : ${remainingSeconds}`,
lastListend: moment(stat.atime).fromNow(),
};
})
);
console.log(collection);
res.json({
allSnongs: collection,
});
});
给予,
[
{
key: 'D:\Music.mp3',
duration: '0 : 27',
lastListend: 'a few seconds ago'
},
{
key: 'D:\Music.mp3',
duration: '0 : 27',
lastListend: 'a few seconds ago'
},
{
key: 'D:\Music.mp3',
duration: '0 : 52',
lastListend: 'a few seconds ago'
},
{
key: 'D:\Music.mp3',
duration: '2 : 12',
lastListend: 'a few seconds ago'
}
]