为什么在循环完成之前要解析objlist?由于for循环是同步的,因此我希望在我的for循环完成后才能运行resolve,但是正在解析带有空对象的列表。
function myFunction(path,files){
return new Promise(function(resolve,reject){
let objlist=[];
files.forEach(function(file,index){
console.log(file)
objlist[index]={};
fs.stat(path + '\\' + file, function(err,stats){
if(err){
console.log(err.code)
console.log(err)
throw err;
}
if(stats.isDirectory()){
objlist[index].file = 'folder'
}
else if(stats.isFile()){
objlist[index].file = 'file'
}
objlist[index].name = file
console.log(objlist[index].name) //gives correct output
objlist[index].size = stats.size
});
})
console.log(objlist); //gives list of empty objects
resolve(objlist);
});
}
最佳答案
如果您不想使用await,则可以使用Promise.all或计数器来了解所有fs.stat
何时解析:
仅使用Promise.all
:
function myFunction(path,files){
return Promise.all(files.map(function(file,index){
console.log(file)
var obj = {};
fs.stat(path + '\\' + file, function(err,stats){
if(err){
console.log(err.code)
console.log(err)
throw err;
}
if(stats.isDirectory()){
obj.file = 'folder'
}
else if(stats.isFile()){
obj.file = 'file'
}
obj.name = file
console.log(objlist[index].name) //gives correct output
obj.size = stats.size
return obj;
});
}))
.then(objList => {
console.log(objlist); //gives list of empty objects
resolve(objlist);
});
}
或使用计数器:
function myFunction(path,files){
return new Promise(function(resolve,reject){
let objlist=[];
var counter = files.length;
files.forEach(function(file,index){
console.log(file)
objlist[index]={};
fs.stat(path + '\\' + file, function(err,stats){
counter--;
if(err){
console.log(err.code)
console.log(err)
throw err;
}
if(stats.isDirectory()){
objlist[index].file = 'folder'
}
else if(stats.isFile()){
objlist[index].file = 'file'
}
objlist[index].name = file
console.log(objlist[index].name) //gives correct output
objlist[index].size = stats.size
if(counter == 0) {
console.log(objlist); //gives list of empty objects
resolve(objlist);
}
});
})
});
}
关于javascript - for循环运行之后的语句for循环完成运行之前的语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49087796/