Promise.method() 函数没有按照我期望的方式工作

Promise.method() function not working the way I expect it to work

我正在编写一些代码来加密两个用户之间的通信通道。 步骤如下

代码使用 crypto 模块,它是核心 nodejs 中为数不多的同步库之一

创建一个密码并return它作为一个承诺

cipher.createCipher = Promise.method((pw) => {
  if (!pw) {
    throw new Error('Passphrase must be provided');
  }
  return crypto.createCipher('aes192', pw);
});

使用 Promise.method()

加密数据
cipher.encryptTextAsPromise = Promise.method((cipher, plainText) => {
  if (!( typeof plainText === 'string')) {
    throw new Error("2nd param must be plain text");
    let cipherText = '';
    cipher.on('readable', () => {
      var data = cipher.read();
      if (data)
        cipherText += data.toString('hex');
    });
    cipher.on('end', () => {
      return cipherText;
    });
    cipher.write(plainText);
    cipher.end();
  }
});

通过回调函数加密数据。

cipher.encryptText = (cipher, plainText, callback) => {
  if (!( typeof plainText === 'string')) {
    throw new Error("2nd param must be plain text");
  }
  try {
    let cipherText = '';
    cipher.on('readable', () => {
      var data = cipher.read();
      if (data)
        cipherText += data.toString('hex');
    });
    cipher.on('end', () => {
      callback(null, cipherText);
    });
    cipher.write(plainText);
    cipher.end();
  } catch (e) {
    callback(e, null);
  }
}

我无法将这两个链接在一起。我拥有的是一个 可怕的反模式 比陷入回调地狱更糟糕

cipher.createCipher('secretWord')
  .then((data) => {
    cipher.encryptTextasPromise(data, 'hello world')
    .then((data) => {
      console.log(data);
    })
    .catch((err) => {
      console.log(err);
    })
  })
  .catch((err) => {
    console.log(err);
  })

mongoDbSearch(username)
  .then((data) => {
    if (data) {
      // Cipher exists, retrieve and encrypt
    }else {
      // Create new cipher and save
      someMongoSave()
        .then((data) => {
          // Cipher exists now, retrieve and encrypt
        })
    }
  })
  .catch((mongoErr) => {
    console.log(mongoErr);
  })

代码有点不完整,因为我仍在努力掌握这个概念。此外,我尝试链接 createCipherencryptTextAsPromise 是 returning undefined 在数据中。我试过将它们写成正常的回调,然后也使用 Promise.promisfyAll(),这感觉就像另一种反模式。

Promise.method 似乎对 createCipher 有意义,但可能对 encryptTextAsPromise.

没有意义

这是一个应该为您指明正确方向的版本,其中提炼了 T.J. Crowder's, Jaromanda X's, and undefined 对该问题的各种评论;更多信息请参见代码注释:

// For this one, `Promise.method` still makes sense (although doing it with
// your own promise is also perfectly reasonable)
cipher.createCipher = Promise.method(pw => {
  if (!pw) {
    throw new Error('Passphrase must be provided');
  }
  return crypto.createCipher('aes192', pw);
});

// For this one, your own promise makes sense
cipher.encryptTextAsPromise = (cipher, plainText) => {
  return new Promise(resolve => {
    if (!( typeof plainText === 'string')) {
      // It's fine to throw here (it will get converted into a rejection),
      // or add `reject` to the arguments list above and call
      // that and return instead:
      // reject(new Error("2nd param must be plain text"));
      // return;
      throw new Error("2nd param must be plain text");
    }
    let cipherText = '';
    cipher.on('readable', () => {
      var data = cipher.read();
      if (data)
        cipherText += data.toString('hex');
    });
    cipher.on('end', () => {
      resolve(cipherText);
    });
    cipher.write(plainText);
    cipher.end();
  });
};

// Usage:
cipher.createCipher('secretWord')
.then(data => cipher.encryptTextAsPromise(data, 'hello world'))
.then(data => console.log(data)) // See 1 below
.catch(err => console.log(err));

mongoDbSearch(username)
.then(data => data || someMongoSave(data)) // You pass `data` to `someMongoSave`, presumably?
.then(data => {
    // Cipher exists, retrieve and encrypt
})
.catch(mongoErr => {
    console.log(mongoErr);
});

另外,重新

if (!( typeof plainText === 'string')) {

JavaScript 中有一个 !== 运算符。只是'说'。 ;-D