1

我一直在寻找一个真正的例子,但我找不到任何一个。我对节点 js 完全陌生。

我正在设置一个使用命令行工具获取密码的服务。

命令行“pw get key”返回与密钥关联的密码。命令行“pw set key password”设置与密钥关联的密码。

我到目前为止的部分代码是:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function cmdPwGet(key) {
  const { stdout, stderr } = await exec(`pw get ${key}`);
  console.log('stdout:', stdout); 
  console.log('stderr:', stderr);
}

async function cmdPwPut(key, passwd) {
  const { stdout, stderr } = await exec(`pw set ${key} ${passwd}`);
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}

class PwService {

    constructor (KEY){
    this.basekey = KEY;
    this.pwd = "";
    }

    setPw (key, passwd) {
      key = this.basekey + "." + key;
      var res = cmdPwPut(key, passwd);
      /* missing bits */
    }

    getPw (key) {
      key = this.basekey + "." + key;
      var res = cmdPwGet(key);
      /* missing bit */
    }
}

module.exports = PwService;

这将在 testcafe 环境中使用。这里我定义了一个角色。

testRole() {
  let pwService = new PwService('a-key-');
  let pw = pwService.getPw('testPW');
  //console.log('pw: '+pw)

  return Role('https://www.example.com/', async t => {
    await t
    .typeText(this.firstInput, 'testPW')
    .typeText(this.secondInput, pw<??>)
    .click(this.selectButton);
    }, { preserveUrl: true });
}

如果我对 pw 使用文字字符串,testcafe 代码就可以工作。

/丢失的位/ 是空的,因为我尝试了许多不同的东西,但没有一个工作!

我想我可以让它与孩子的 *Sync 版本一起工作。但由于这是在可能并行运行的 testcafe 内,我更喜欢异步版本。

有什么建议吗?我知道真正理解 node.js 中的 Promise 之类的东西,但我无法摆脱这一点。

看来这应该是 node.js 专家的标准练习。

4

1 回答 1

5

Async/Await 只是让异步代码看起来像同步代码,你的代码仍然异步执行。Async\Await 函数的返回结果cmdPwGet是 a Promise,而不是password你想象的那样。

的执行结果cmdPwGet是一个承诺

async function cmdPwGet(key) {
  const { stdout, stderr } = await exec(`pw get ${key}`);
  return stdout;
}

使getPw异步/等待

  async getPw(key) {
        key = this.basekey + "." + key;
        var res = await cmdPwGet(key);
        return res;
    }

获取密码

testRole() {
  let pwService = new PwService('a-key-');

  return Role('https://www.example.com/', async t => {
    // get your password with await
    let pw = await pwService.getPw('testPW');
    await t
    .typeText(this.firstInput, 'testPW')
    .typeText(this.secondInput, pw<??>)
    .click(this.selectButton);
    }, { preserveUrl: true });
}
于 2017-12-03T07:26:29.897 回答