나는 대상 폴더 내에서 파일을 재귀 적으로 찾고 "file", "error", "end"이벤트를 반환하는 findit이라는 모듈을 사용하고 있습니다.
const finder = findit("folder/");
finder.on("file", (file) => {});
finder.on("error", ((error) => {});
finder.on("end", () => {});
파인더가 모든 파일을 찾을 때 종료 이벤트가 호출되지만 파일 이벤트 내에서 비동기 작업을 수행하며 내부에 무언가가있는 경우에만 파일을 분리합니다.
const finder = findit("folder/");
let neededFiles = [];
finder.on("file", (file) => {
// async operation here to store only the files that i want
// neededFiles = [...neededFiles, file];
});
finder.on("error", ((error) => {});
finder.on("end", () => {
console.log(neededFiles); // empty array
});
비동기 작업이 아직 완료되지 않았으므로 neededFile이 비어 있습니다. 내 질문은 : 종료 이벤트에서 비동기 작업을 기다리려면 어떻게해야합니까?
감사.
앱의 스크래치 만 제공 했으므로이를 중심으로 구축하고이를 비동기 부분을 처리하겠다는 약속으로 래핑하는 방법을 보여주었습니다.
function find(folder){
return new Promise((resolve, reject) => {
const finder = findit(folder);
const files = [];
finder.on("file", (file) => {
//do stuff like
//files.push(valueOrPromise);
//or
//files.push( find(anotherPath) );
});
finder.on("error", reject);
finder.on("end", () => {
//this line finally "returns" the result.
//to this point you can modify files as you wish
resolve( Promise.all(files) );
//hint, if you're working with recursive stuff, you may have nested Arrays, so you should flatten the result
//resolve( Promise.all(files).then(values => values.reduce((a,b) => a.concat(b), [])) )
});
})
}
보통 사람들은이 시점에서 묻습니다. 약속이 왜 필요한가요? 비동기 작업의 상태 관리를 구현하기 때문입니다. 그렇다면 왜 직접 구현하고 싶습니까?
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다