Promise.promisify 后无法读取未定义的属性

Ayu*_*ISM 2 javascript node.js promise bluebird

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, {});
    });
Run Code Online (Sandbox Code Playgroud)

如果我在 之后放置一个断点const fastPutProm = Promise.promisify(sftp.fastPut);fastPutProm则是一个带有三个参数的函数。但是当我尝试运行此代码时,出现TypeError: Cannot read property 'fastPut' of undefined错误。我在这里做错了什么?

jfr*_*d00 5

该错误意味着您的sftp值是undefinedso 当您尝试传递sftp.fastPut给该promisify()方法时,它会生成一个错误,因为您正在尝试引用undefined.fastPutwhich 是TypeError.

因此,解决方案是备份几个步骤并找出其中sftp没有所需值的原因。


另一种可能性是错误来自模块内部,这是因为 的实现sftp.fastPut正在引用this它期望的sftp. 您承诺的方法没有保留this. 您可以通过将代码更改为:

const fastPutProm = Promise.promisify(sftp.fastPut, {context: sftp});
Run Code Online (Sandbox Code Playgroud)

  • @AyushISM - 你能告诉我们`sftp.fastPut()` 的代码吗?它是否在实现中使用了 `this` 的值?如果是这样,您必须将 `sftp` 上下文传递给 `promisify()` 方法。请参阅 [Bluebird 的 `.promisify()`](http://bluebirdjs.com/docs/api/promise.promisify.html) 上的 `context` 选项。也许试试这个:`const fastPutProm = Promise.promisify(sftp.fastPut, {context: sftp});` (2认同)