【问题标题】:Resurrection in node async function NodeJs节点异步函数NodeJs中的复活
【发布时间】:2021-07-19 05:43:53
【问题描述】:

我正在尝试使用 nodejs 通过 sftp 远程删除文件的功能。

我的功能是这样的

function dropdir(path){
                sftp.readdir(path, async(err, files)=>{
                    if(err)  console.log(err);//{ callback(err);  return err;}
                    
                    if(!files.length){
                    
                        await sftp.rmdir(path)
                    }else {
                        for (let i = 0; i < files.length; i++) {
                            sfile= files[i];
                        
                            if(sfile.attrs.size == 4096){
                                await dropdir(path+"/"+ sfile.filename);   //recalling function with await
                                console.log(path);  //console.log of current working path
                            }else{
                                file_path= path+"/"+ sfile.filename;
                                await sftp.unlink(file_path)
                            
                            }
                        }
                        await sftp.rmdir(path)
                    }
                });

当我用 await 调用上述函数时,它不会等待 self 完成。

在 console.log 中我得到了

/home/ubuntu/hiiii
/home/ubuntu/hiiii/Links
/home/ubuntu/hiiii/Links/Links
/home/ubuntu/hiiii/Links/Links/Links 

这意味着 dropdir 没有等待最后一个孩子完成

简单来说,这个函数是在目录方向上向前移动(父到子),而不是反向(子到父)

【问题讨论】:

    标签: node.js asynchronous async-await sftp


    【解决方案1】:

    尝试将函数声明为async

    此外,对于sftp.readdir,将该回调样式函数转换为带有util.promisifypromisifed 函数。

    • 等待promisifedReadDir 将结果分配给const files

    回调中的代码现在可以在同一级别上并且awaited on。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多