Cannot read property of undefined after Promise.pr

2019-07-31 02:36发布

问题:

let nasPath = "";
return getFamInfo(args.familyID)
    .then(function (famInfo) {
        nasPath = //some code involving famInfo here
        return getSFTPConnection(config.nasSettings);
    }).then(function (sftp) {
      const fastPutProm = Promise.promisify(sftp.fastPut);
      return fastPutProm(config.jpgDirectory, nasPath, {});
    });

If I put a breakpoint after const fastPutProm = Promise.promisify(sftp.fastPut);, fastPutProm is a function with three arguments. But when I try to run this code, I get a TypeError: Cannot read property 'fastPut' of undefined error. What am I doing wrong here?

回答1:

That error means that your sftp value is undefined so when you try to pass sftp.fastPut to the promisify() method, it generates an error because you're trying to reference undefined.fastPut which is a TypeError.

So, the solution is to back up a few steps and figure out why sftp doesn't have the desired value in it.


Another possibility is that the error is coming from inside the module and it's because the implementation of sftp.fastPut is referencing this which it expects to be sftp. Your method of promisifying is not preserving the value of this. You can fix that by changing your code to:

const fastPutProm = Promise.promisify(sftp.fastPut, {context: sftp});