如何在节点 js 中正确使用等待/异步与 for 循环
Posted
技术标签:
【中文标题】如何在节点 js 中正确使用等待/异步与 for 循环【英文标题】:How to properly use await/async with for loops in node js 【发布时间】: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
的组合,它工作得很好,问题是你传递的是普通的旧异步回调而不是使用(和await
ing ) 承诺。
【参考方案1】:
此答案不会修复您的代码,而只是为了消除任何误解:
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 );
【讨论】:
【参考方案2】:有大量时间来玩弄您的代码。 我会这样写,我做了很多改变。它有效
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\1.mp3',
duration: '0 : 27',
lastListend: 'a few seconds ago'
,
key: 'D:\Music\1.mp3',
duration: '0 : 27',
lastListend: 'a few seconds ago'
,
key: 'D:\Music\1.mp3',
duration: '0 : 52',
lastListend: 'a few seconds ago'
,
key: 'D:\Music\1.mp3',
duration: '2 : 12',
lastListend: 'a few seconds ago'
]
【讨论】:
不要在回调中使用collection.push(…)
,而是使用return
的值并使用const collection = await Promise.all(…)
@Bergi +1,这样更好以上是关于如何在节点 js 中正确使用等待/异步与 for 循环的主要内容,如果未能解决你的问题,请参考以下文章