【问题标题】:Is it good to use Promise this way?以这种方式使用 Promise 好吗?
【发布时间】:2023-03-14 11:28:02
【问题描述】:

我试图理解和掌握承诺,但我遇到了一个问题,我不确定这是否是正确的做事方式。

我正在使用 nodejs,我有以下内容: 一个数据库和一个模块,我在其中对数据库进行操作。有一次,我试图在数据库中创建一个新用户,并在创建用户之后在另一个表中为该用户创建另一个条目以及其他详细信息。

passport.use('local-signup', new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password',

  },
  function(username, password, done) {

    // Before creating the user access Sequlize beforeCreate method so we can encrypt the password
    User.beforeCreate(function(req) {
      console.log('Encryptying password for user ',req.username)
      return encryptPass(req.password)
      .then(success => {
        req.password = success;
      })
      .catch(err => {
        if (err) console.error(err);
      });
    });

    User.create({
      username: username,
      password: password
    }).then(function(createdUser) {
      console.log(createdUser);
      UserDetails.create({
        id:createdUser.dataValues.id
      }).then((data)=>{
        console.log(data);
        return done(null,createdUser);
      }).catch((error)=>{
        console.log(error)
        return done(error)
      })
    })
    .catch(function(error) {
      console.error(error)
      return done(`${error.message}.`);
    });
  }
));

当我有这样的事情时,这是使用承诺的正确方法吗?

如果您需要更多信息,请告诉我,我会尽量让一切更清楚。

最好的问候, 维克多

【问题讨论】:

  • 我认为在 JavaScript 中使用 Promises 没有正确或错误的方式
  • 能否提供这里封装的函数。大概是具有参数done 的函数。另外,done 是否像 Promise resolve
  • JS ES6 Promise Chaining的可能重复
  • @Nicholas Kyriakides 只要你知道不要嵌套太多,结果是回调地狱,或者可能开始使用新的async/await 函数,我相信你的代码看起来很漂亮和可读,更多信息async/await你可以访问这个网站developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @FelixFong 我应该看看并尝试学习 async/await :) 我刚刚将表单回调移动到 Promise,因为我仍然是初级但 async/await 看起来是一个新的好东西.谢谢。

标签: javascript node.js promise es6-promise


【解决方案1】:

你可以稍微简化一下,因为你可以删除内部catch块,只需要返回内部Promise

User.create({
    username: username,
    password: password
}).then(function (createdUser) {
    console.log(createdUser);
    return UserDetails.create({
        id: createdUser.dataValues.id
    }).then((data) => {
        console.log(data);
        return done(null, createdUser);
    })
}).catch(function (error) {
    console.error(error);
    return done(`${error.message}.`);
});

休息看起来不错

【讨论】:

    【解决方案2】:

    谢谢大家,基于 cmets,我最终得到了以下代码。尽管我试图避免回调地狱问题,但它看起来仍然有点像它,但由于需要调用两个 Promise,我认为这是一个很好的解决方案,并且不会嵌套太多:

     // Local sign-up strategy
      passport.use('local-signup', new LocalStrategy({
        usernameField: 'username',
        passwordField: 'password',
    
      },
      function(username, password, done) {
    
        // Before creating the user access Sequlize beforeCreate method so we can encrypt the password
        User.beforeCreate(function(req) {
          console.log('Encryptying password for user ',req.username)
          return encryptPass(req.password)
          .then(success => {
            req.password = success;
          })
          .catch(err => {
            if (err) console.error(err);
          });
        });
    
        User.create({
          username: username,
          password: password
        }).then(function(createdUser) {
          console.log(createdUser);
          return createdUser;
        }).then((userData) =>{
          UserDetails.create({
            id:userData.dataValues.id
          }).then((userDetails)=>{
            return done(null,userData)
          })
        }).catch(function(error) {
          console.error(error)
          return done(`${error.message}.`);
        });
      }
    ));
    

    谢谢你, 维克多

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-08
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 2014-11-21
      相关资源
      最近更新 更多