node.jsftplftp

Promisify node-ftps command


Im a trying to promisify a node-ftps function in order to use async/await. I am referring to this github link which explains how it should be done. I came up with the following code but it is still not working.

My promisified function :


const ftpGetFile = async (ftps, source, destination) => {

    console.log(`FTP MGET ${source} => ${destination}`)
    return ftps.raw(`mget -e -O ${destination} ${source}`).exec((error, result) => {
        return new Promise((resolve, reject) => {
            if (error) {
                console.log("ftp fget error", error)
                reject(error)
            } else {
                console.log("ftp fget succss", result)

                resolve(result)
            }
        })
    })
}

And how I call it

for (let index = 0; index < listToSync.length; index++) {

    // ....
    await ftpGetFile(ftp, source, destination)
    // ....
}


Solution

  • You'll want to return the promise itself, which then resolves in the callback to exec:

    const ftpGetFile = async (ftps, source, destination) => {
      console.log(`FTP MGET ${source} => ${destination}`)
    
      return new Promise((resolve, reject) => {
        ftps.raw(`mget -e -O ${destination} ${source}`).exec((error, result) => {
          if (error) {
            console.log("ftp fget error", error)
            reject(error)
          } else {
            console.log("ftp fget succss", result)
            resolve(result)
          }
        })
      })
    }