如何在回调中打破循环
How to break out a loop in a callback
嗨,我怎样才能跳出 for 循环?我希望能够在 if 语句
的回调中突破它
我希望这个程序在给定的目录中创建一个文件夹,每次它抛出错误时我希望它更改文件夹名称并添加一个数字,所以当它说该文件夹已经存在时,它'我将创建一个唯一的文件夹名称,直到它不抛出错误。
I will check for the error code later help me solve this first
const path = require('path');
function folder(folderName) {
for (let i = 1; i <= 10; i++) {
let pathNumber = i;
let fullPath = folderName + pathNumber;
fs.mkdir(path.join("D:", fullPath), (err) => {
if (!err) {
return; // I want to break out of the loop here
}
})
}
}
folder("folder");
您不能以这种方式编写代码,因为 for
循环在调用任何 fs.mkdir()
回调之前已经完成。它们是异步的,稍后发生。
如果要执行循环的一次迭代,包括 fs.mkdir()
,然后再继续执行任何其他循环,则可以使用 async/await
和 fs.promises.mkdir()
。
下面是 fs.promises.mkdir()
的解决方案。我还为您尝试的所有 10 个子目录名称都已存在的情况添加了错误处理。
async function folder(folderName) {
let lastError;
for (let pathNumber = 1; pathNumber <= 10; pathNumber++) {
let fullPath = path.join("D:", folderName + pathNumber);
try {
await fs.promises.mkdir(fullPath);
return fullPath;
} catch(e) {
lastError = e;
// ignore error so we keep trying other numbers
}
}
throw lastError;
}
folder("folder").then(fullPath => {
console.log(`dir created: ${fullPath}`);
}).catch(err => {
console.log(err);
});
没有 await 更简单
const numFolders = 10,
folders = Array.from(Array(numFolders), (_,i) => `folder${i+1}`), len = folder.length;
let cnt = 0;
const makeFolder = () => {
if (cnt >= len) return; // stop because done
fs.mkdir(path.join("D:", fullPath), (err) => {
if (err) {
makeFolder(); // only call again if error
}
cnt++
}
makeFolder()
嗨,我怎样才能跳出 for 循环?我希望能够在 if 语句
的回调中突破它我希望这个程序在给定的目录中创建一个文件夹,每次它抛出错误时我希望它更改文件夹名称并添加一个数字,所以当它说该文件夹已经存在时,它'我将创建一个唯一的文件夹名称,直到它不抛出错误。
I will check for the error code later help me solve this first
const path = require('path');
function folder(folderName) {
for (let i = 1; i <= 10; i++) {
let pathNumber = i;
let fullPath = folderName + pathNumber;
fs.mkdir(path.join("D:", fullPath), (err) => {
if (!err) {
return; // I want to break out of the loop here
}
})
}
}
folder("folder");
您不能以这种方式编写代码,因为 for
循环在调用任何 fs.mkdir()
回调之前已经完成。它们是异步的,稍后发生。
如果要执行循环的一次迭代,包括 fs.mkdir()
,然后再继续执行任何其他循环,则可以使用 async/await
和 fs.promises.mkdir()
。
下面是 fs.promises.mkdir()
的解决方案。我还为您尝试的所有 10 个子目录名称都已存在的情况添加了错误处理。
async function folder(folderName) {
let lastError;
for (let pathNumber = 1; pathNumber <= 10; pathNumber++) {
let fullPath = path.join("D:", folderName + pathNumber);
try {
await fs.promises.mkdir(fullPath);
return fullPath;
} catch(e) {
lastError = e;
// ignore error so we keep trying other numbers
}
}
throw lastError;
}
folder("folder").then(fullPath => {
console.log(`dir created: ${fullPath}`);
}).catch(err => {
console.log(err);
});
没有 await 更简单
const numFolders = 10,
folders = Array.from(Array(numFolders), (_,i) => `folder${i+1}`), len = folder.length;
let cnt = 0;
const makeFolder = () => {
if (cnt >= len) return; // stop because done
fs.mkdir(path.join("D:", fullPath), (err) => {
if (err) {
makeFolder(); // only call again if error
}
cnt++
}
makeFolder()