为什么insde等待,使用Promise.resolve返回或不返回是好的,而不是带有promises函数

时间:2017-10-23 03:00:39

标签: javascript async-await es6-promise

我已将旧的纯承诺函数转换为后端apollo服务器中的asyn等待函数,由反应应用程序使用

一切运行良好,但我对async / await函数中的行为魔术有疑问:

这是我的旧代码:

const signIn = (args) =>  {

  return new Promise((resolve, reject) => {
    return User.findOne({ where: {nick: args.nick }})
      .then((user) => {
        if (user == null) {
          return reject({
            code: 'error.loginNick',
            message: 'Authentication failed. User not found.'
          });
        }

        if (user.password != args.password) {
          console.log('pass incorrect:' +  args.password + ' = '+ user.password);
          return reject({
            code: 'error.loginPassword',
            message: 'Wrong password.'
          });
        }
        return resolve(createToken({ id: user.id, nick: user.nick }));
      })
      .catch(err => {
        reject(err);
      });
  });
};

createToken函数:

exports.createToken = payload => (
  jwt.sign(payload, config.auth.secret, {
    expiresIn: config.auth.expiresIn
  })
);

在我的singIn函数中,我需要调用最后一个函数:

resolve(createToken.....

如果我不使用解决方案,我的应用程序无法正常工作,因为等待承诺。在此之前没有什么奇怪的,但是我的新重写函数signIn中的行为是不同的,使用异步。

我全新的异步功能:

async function signIn (args) {

  try {

    let err;
    if (!args.nick) {
      err = {code: 'nick.empty', message: 'Nick is empty.'};
    } else if (!args.password) {
      err = {code: 'password.empty', message: 'You have to provide a password.'};
    }
    if (err) {
      throw(err);
    }

    // Find the user
    const user = await User.findOne({ where: {nick: args.nick }});


    if (user == null) {
      err = {
        code: 'error.loginNick',
        message: 'Authentication failed. User not found.'
      };
      throw (err);
    }

    if (user.password != args.password) {
      console.log('pass incorrect:' +  args.password + ' = '+ user.password);
      err = {
        code: 'error.loginPassword',
        message: 'Wrong password.'
      };
      throw (err);
    }
    //return Promise.resolve(createToken({ id: user.id, nick: user.nick })); <-- workin ok too
    return createToken({ id: user.id, nick: user.nick });

  } catch(err) {
      throw (err);
  }
}

export { Customer, Tour, User, Auth , signIn };

如果我使用这两种选择,两者都运作良好!为什么?好的承诺我很清楚它是有效的,但是没有承诺也行得正常,不像我以前的承诺那样行为

替代方案1没有承诺:

return createToken({ id: user.id, nick: user.nick });

为什么不需要这里的承诺?,如果出现错误,那么twhrow会去哪里?

备选2,承诺:

return Promise.resolve(createToken({ id: user.id, nick: user.nick }));
如果出现错误,那么twhrow会在哪里? 最后一种选择是反模式?

0 个答案:

没有答案
相关问题