superagent / supertest with async / await

Gob*_*ins 7 javascript node.js async-await superagent es6-promise

目标是auth正确设置变量以供进一步使用,因此我想重构函数 loginUser:

function loginUser(user, request, auth) {
  return function(done) {
    request
      .post('/users/login')
      .send(credentials)
      .expect(200)
      .end(onResponse);

    function onResponse(err, res) {
      auth.token = res.body.token;
      return done();
    }
  };
}


 loginUser(user, request, auth)(function() {
  request.get(testUrl)
    .set('Authorization', `bearer ${auth.token}`)
    .expect(200, done);
});
Run Code Online (Sandbox Code Playgroud)

像这样使用异步/等待(没有回调):

auth = await loginUser(user, request);
request.get(testUrl)
    .set('Authorization', `bearer ${auth.token}`)
    .expect(200, done);
Run Code Online (Sandbox Code Playgroud)

但是我正在努力auth正确返回/设置(如果我auth作为参数或返回值传递都没有关系)。

我尝试的是这样的东西:

async function loginUser(user, request) {
  let auth;
  await request
    .post('/users/login')
    .send(credentials)
    .expect(200)
    .end(onResponse);

  function onResponse(err, res) {
    auth.token = res.body.token;
  }
  return auth;
}
Run Code Online (Sandbox Code Playgroud)

auth从未正确设置。

Lev*_*sov 10

不要使用“结束”语法,这是用于回调:

const response = await request.post(...)
  .expect(200)
const {body: {token}} = response
return token
Run Code Online (Sandbox Code Playgroud)

基本上它应该看起来像同步代码