【发布时间】:2020-02-04 09:44:42
【问题描述】:
我现在很困惑。我花了最后一个小时尝试根据创建日期对目录进行排序。这是我所在的位置:
const
fsPromises = require('fs').promises
let
arr = []
fsPromises.readdir(rootPath, 'utf8')
.then((array)=>{
array.forEach((dir)=>{
console.log(dir) // executed last for some reason
fsPromises.stat(`./Projects/${dir}`)
.then((stats)=>{
arr.push([stats.birthtimeMs, dir])
})
})
})
.then(()=>{
arr = arr.sort((a,b)=>{
Math.floor(a[0])-Math.floor(b[0])
})
})
.then(console.log(arr))
我不知道为什么最后的 then 会吐出一个无序数组。
Promise 对我来说是新的,所以我不完全确定是不是 Promise 链导致了问题,但直到第二个 then 之前一切似乎都很好。
任何帮助将不胜感激。
【问题讨论】:
-
尝试在第一个
.then中添加console.log(arr)) -
最后的
.then()应该是打印undefined,而不是一个数组。你应该先看到它的输出。 -
@mph85 在第一个
then中粘贴console.log的问题在于fsPromises.stat也是异步的。我对 Node、Electron、FS 和 Promises 完全陌生,所以这真的让我陷入了一个循环:( -
@PatrickRoberts 哦该死,对不起。在我的代码中,我有
let arr = [],你说得对,它出于某种原因首先运行。承诺的全部目的不是按顺序运行thens吗? -
@BugWhisperer 你不是在等待循环内创建的承诺。您应该将它们分组并等待它们在 Promise.all 中完成。之后,您的 then 将具有正确的值。
标签: arrays node.js sorting promise fs