代码之家  ›  专栏  ›  技术社区  ›  paulmiller3000

等待数组中每个项的承诺

  •  0
  • paulmiller3000  · 技术社区  · 6 年前

    我正在节点中使用ssh2 sftp客户机下载一系列文件。下载完这些文件后,我需要检查每个文件是否是csv文件,然后检查我的数据库以查看它是否以前导入过。

    我用的是承诺,在排序上有困难。我想经过几个小时的研究,我已经接近尾声了,但还不能完全理解。

    代码如下:

    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)
            })
        })
    });
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   spakmad    6 年前

    importFile

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

    then Promise promiseChain Promise.resolve()

    reduce

    myFiles.reduce((acc, file) => acc.then(() => importFiles(file))), Promise.resolve())
    
        2
  •  1
  •   Jordan Davidson    6 年前

    [undefined, undefined...] console.log() isFileCsv(file).then((result) => {

        3
  •  0
  •   Daphoque    6 年前

    const importFile = function(file){
    
        return new Promise(function(resolve, reject){
    
            isFileCSV(file).then((result) => {
                console.log(`01a File ${file} ends with csv? ${result}`);
                result = result.toLowerCase();
    
                if (result === 'false') {
                    console.log(`01b ${result} = Not csv, log it and skip to next.`);
                } else if (result === 'true') {
                    console.log(`01b ${result} = It is csv, go to next step`);
                }
    
                wasFileImported('file').then((result) => {
                    console.log('03 checked import, result: ', 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');                         
                    }
    
                    return resolve(result);
                }) 
    
            });
    
        });     
    }