gpt4 book ai didi

javascript - 等待数组中每个项目的 promise

转载 作者:行者123 更新时间:2023-12-01 01:49:45 26 4
gpt4 key购买 nike

我在 Node 中使用 ssh2-sftp-client 来下载一系列文件。下载文件后,我需要检查每个文件,看看它是否是 CSV,然后检查我的数据库,看看它是否是之前导入的。

我正在使用 Promise,但在排序方面遇到了麻烦。我想经过几个小时的研究我已经很接近了,但还不能完全理解。

代码如下:

const isFileCSV = (filename) => {

return new Promise( (resolve, reject) => {
if (filename.endsWith('.csv')) {
result = 'true';
resolve(result);
} else {
result = 'false';
resolve(result);
}
});
}

const wasFileImported = (filename) => {
// Return a new promise
return new Promise( (resolve, reject) => {
// Core function
con.query(`CALL wasFileImported('${filename}')`, (err, results) => {
console.log('02 Checking if file was previously imported.');
if (err) {
logEntry('error', `Error searching database: ${err}`);
reject(Error('false'));
} else {
result = results[0][0]['importCheck'];
resolve(result);
}
})
});
}

const importFile = (file) => {
isFileCSV(file).then((result) => {
console.log(`01a File ${file} ends with csv? ${result}`);
result = result.toLowerCase();
return result;
}).then((result) => {
if (result === 'false') {
console.log(`01b ${result} = Not csv, log it and skip to next.`);
return;
} else if (result === 'true') {
console.log(`01b ${result} = It is csv, go to next step`);
return result;
}
}).then((result) => {
wasFileImported('file').then((result) => {
console.log('03 checked import, result: ', result);
return result.toLowerCase();
}).then((result) => {
switch(result) {
case 'false':
console.log('04a download file and log it');
break;
case 'true':
console.log('04b skip it and log the skip');
break;
default:
console.log('04c unknown error, log the skip');
}
})
})
}

logEntry('info', `attempting to connnect to ${config.destination.host}`);
console.log('00 start');

sftp.connect(crmConfig).then(() => {
logEntry('info', `connected to ${config.destination.host}`);
return sftp.list(ordersUrl);
}).then((data) => {
fileList = [];
Object.entries(data).forEach(([key, val]) => {
fileList.push(val['name']);
});
return fileList;
}).then((fileList) => {
let promises = [];

fileList.forEach((file) => {
promises.push(importFile(file));
});

Promise.all(promises).then(function(results) {
console.log('Done');
}).catch(function(err) {
console.log('Error');
});
});

我期望看到的是以下内容:

00 start
01a File daily.csv ends with csv? true
01b true = It is csv, go to next step
02 Checking if file was previously imported.
03 checked import, result: FALSE
04a download file and log it
01a File daily072418.csv ends with csv? true
01b true = It is csv, go to next step
02 Checking if file was previously imported.
03 checked import, result: FALSE
04a download file and log it
01a File test.csw ends with csv? false
01b false = Not csv, log it and skip to next.
02 Checking if file was previously imported.
03 checked import, result: FALSE
04a download file and log it
Done

我实际得到的是:

00 start
01a File daily.csv ends with csv? true
01a File daily072418.csv ends with csv? true
01a File test.csw ends with csv? false
01b true = It is csv, go to next step
01b true = It is csv, go to next step
01b false = Not csv, log it and skip to next.
Done
02 Checking if file was previously imported.
03 checked import, result: FALSE
04a download file and log it
02 Checking if file was previously imported.
03 checked import, result: FALSE
04a download file and log it
02 Checking if file was previously imported.
03 checked import, result: FALSE
04a download file and log it

早期版本没有使用Promise.all,但仍然生成相同的结果。我还尝试更改解析以返回 wasFileImported 和 isFileCSV,但随后我只得到“00 Start”,然后是“Done”,中间没有执行。

显然,我没有按照我的意图正确地迭代数组。最好的方法是什么,以便一切都按顺序完成?

编辑对于任何需要它的人来说,这是最终的工作代码,感谢 @jordan-peterson 和 @spakmad:

const isFileCSV = (filename) => {
return new Promise( (resolve, reject) => {
if (filename.endsWith('.csv')) {
result = 'true';
resolve(result);
} else {
result = 'false';
resolve(result);
}
});
}

const wasFileImported = (filename) => {
// Return a new promise
return new Promise( (resolve, reject) => {
// Core function
con.query(`CALL wasFileImported('${filename}')`, (err, results) => {
console.log('02 Checking if file was previously imported.');
if (err) {
logEntry('error', `Error searching database: ${err}`);
reject(Error('false'));
} else {
result = results[0][0]['importCheck'];
resolve(result);
}
})
});
}

const importFile = (file) => {
return isFileCSV(file).then((result) => {
console.log(`01a File ${file} ends with csv? ${result}`);
result = result.toLowerCase();
return result;
}).then((result) => {
if (result === 'false') {
console.log(`01b ${result} = Not csv, log it and skip to next.`);
return;
} else if (result === 'true') {
console.log(`01b ${result} = It is csv, go to next step`);
return result;
}
}).then((result) => {
return wasFileImported('file').then((result) => {
console.log('03 checked import, result: ', result);
return result.toLowerCase();
}).then((result) => {
switch(result) {
case 'false':
console.log('04a download file and log it');
break;
case 'true':
console.log('04b skip it and log the skip');
break;
default:
console.log('04c unknown error, log the skip');
}
})
})
}

console.log('00 start');

sftp.connect(crmConfig).then(() => {
logEntry('info', `connected to ${config.destination.host}`);
return sftp.list(ordersUrl);
}).then((data) => {
fileList = [];
Object.entries(data).forEach(([key, val]) => {
fileList.push(val['name']);
});
return fileList;
}).then((fileList) => {
let promiseChain = Promise.resolve()

fileList.forEach((file) => {
promiseChain = promiseChain.then(() => {
return importFile(file)
})
})
});

最佳答案

您正在连续三次调用异步方法 importFile,因此它会同时遍历这些方法。如果你想一个接一个地执行,我喜欢做的就是这个。

let promiseChain = Promise.resolve()
myFiles.forEach((file) => {
promiseChain = promiseChain.then(() => {
return importFile(file)
}
}

循环上的每次迭代都会将另一个 then 附加到 promiseChain 中的 Promise,直到第一个 then 返回。附加的第一个 then 被提前到立即,因为此时 promiseChainPromise.resolve()

这也可以通过 reduce 来完成。

myFiles.reduce((acc, file) => acc.then(() => importFiles(file))), Promise.resolve())

关于javascript - 等待数组中每个项目的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51638710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com