【问题标题】:Return a value from this promise从这个 Promise 返回一个值
【发布时间】:2017-06-18 13:07:13
【问题描述】:

这可能是一个愚蠢的问题,但学校里没有人知道该怎么做。 我有这段代码可以完美运行(它发送对象表potentials,我可以在客户端使用它)但我记得我还需要另一个(userData)。 所以我尝试将其声明为const,然后在我的res.render 之前将其记录下来,但它是undefined。到目前为止,我们的学生组对 Promise 还不是很熟悉,所以也许我们在这里遗漏了一些东西。 无论如何,这是我的代码,有什么帮助吗?谢谢你。

function matchaSearch (pool, username) {
return suggestUsers(pool, username)
  .then((searcherInfos) => {
     userData = [...searcherInfos]
    if (userData[0].sex === 'm' && userData[0].orientation === 's') {
      return lookForSF(pool, username)
    } else if ((userData[0].sex) && userData[0].orientation === 'b') {
      return lookForbothCauseImB(pool, username)
    } else if ((userData[0].sex) === 'f' && userData[0].orientation === 's') {
      return lookForSM(pool, username)
    } else if ((userData[0].sex) === 'm' && userData[0].orientation === 'g') {
      return lookForGM(pool, username)
    } else if ((userData[0].sex) === 'f' && userData[0].orientation === 'g') {
      return lookforGF(pool, username)
    }
  })
  .then((rows) => {
    var potentials = rows;
    return (potentials)
  })
}

router.post('/matchaSearch', function (req, res) {
const userData = []
matchaSearch(pool, session.uniqueID)
.then((potentials) => {
  console.log(userData);
  res.render('./userMatch', {potentials, userData})
})
.catch((err) => {
  console.error('error', err)
  res.status(500).send("we don't have any suggestions for you so far")
})
})

【问题讨论】:

  • userData 是空数组吗?
  • 其实我刚刚找到了答案。很抱歉发布这个。我可以在 res.render 之前从变量中调用我的函数,然后移动它。
  • 您的问题得到解答了吗?

标签: javascript node.js express promise pug


【解决方案1】:

你没有以正确的方式使用Promise,没有什么比 return 更好的了。您的代码示例可以是

var searcherInfosPro = (searcherInfos)=>{
  return new Promise((fullfill,reject)=>{
    userData = [...searcherInfos];
    if (userData[0].sex === 'm' && userData[0].orientation === 's') {
      fullfill([pool,username]);
    }else if((userData[0].sex) && userData[0].orientation === 'b') {
      fullfill([pool,username]);
    }else{
      reject((new Error("Some error detected"));
    }
  });
}

你可以调用它使用

suggestUsers(pool, username)
  .then(searcherInfosPro)
  .then((rows) => {
    var [pool,username] = rows;
    return (potentials)
  })
  .catch((ex)=>{
    console.log(ex.message);
  });

查看您的代码,我并不太清楚,所以上面的代码是关于如何正确使用 promise 并将数据传递给下一个的简短版本。还要记住始终使用catch 处理任何错误。

从上面的代码中,else 案例将调用并出错并打印 Some error detected

【讨论】:

    【解决方案2】:

    这是我所做的,它对我有用:

    router.post('/matchaSearch', function (req, res) {
    
    matchaSearch(pool, session.uniqueID)
    .then((potentials) => {
      userData = suggestUsers(pool, username)
        .then((rows) => {
          res.render('./userMatch', {potentials, rows})
        })
    
    
    })
    .catch((err) => {
      console.error('error', err)
      res.status(500).send("we don't have any suggestions for you so far")
    })
    })
    

    【讨论】:

      【解决方案3】:

      您似乎找到了部分问题的答案。我想我会向您展示一种更简洁的方法,它提供了以下改进:

      1. 用查找表替换所有 if/else 子句。
      2. 消除了尝试将 userData 设置为更高范围的变量的副作用编程,以便您以后可以使用它。
      3. 如何从一个 Promise 中返回多个值(通过将它们包装在一个对象中)。

      代码:

      const fnLookup = {
          'ms': lookForSF,
          'fs': lookForSM,
          'mg': lookForGM,
          'fg': lookForGF,
          'mb': lookForbothCauseImB,
          'fb': lookForbothCauseImB
      };
      
      
      function matchaSearch (pool, username) {
          return suggestUsers(pool, username).then(searcherInfos => {
              let userData = [...searcherInfos];
              let fn = fnLookup[userData[0].sex + userData[0].orientation];
              if (fn) {
                  return fn(pool, username).then(potentials => {
                      return {potentials, userData};
                  });
              } else {
                  throw new Error(`Unexpected values for sex ${userData[0].sex} or orientation ${userData[0].orientation}`);
              }
          });
      }
      
      router.post('/matchaSearch', (req, res) => {
          matchaSearch(pool, session.uniqueID).then(data => {
              console.log(data.userData);
              res.render('./userMatch', data);
          }).catch(err => {
              console.error('error', err)
              res.status(500).send("we don't have any suggestions for you so far")
          });
      });
      

      【讨论】:

        猜你喜欢
        • 2014-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-17
        相关资源
        最近更新 更多