如何将此功能作为承诺?

时间:2016-11-12 16:38:01

标签: javascript

我使用快递来路线

app.get('/api/users/:username', (req, res) => {
  let username = req.params.username;
  findUserInApi(username)
    .then(foundUser => {
      if (foundUser) {
        res.status(403).send('User not found in api yet');
      }else{
        res.json(foundUser);
      }
    });
});

我希望findUserInApi成为一个承诺,因为我需要等待该函数内部的提取。

这是findUserInApi

const findUserInApi = (username) => {
  findChattersPerRole()
    .then(chattersPerRole => {
      console.log(`${username} should\'ve been added by now...`);
      //console.log(chattersPerRole);
      let wantedUser = find(chattersPerRole, {username});
      if (!wantedUser) {
        console.log(`${wantedUser} wasn't found m8`);
        return Promise.resolve(null);
      }
      console.log('wanteduser is: ', wantedUser);
      getUserByUsername(wantedUser.username)
        .then(foundUser => {
          console.log('founduser is: ', foundUser);
          return Promise.resolve(foundUser);
        });
    });
};

我曾经在找不到时返回null或者在找到时返回foundUser,但是我试图通过返回Promise.resolve来做出承诺。我不确定如何解决这个问题...

1 个答案:

答案 0 :(得分:2)

您需要返回整个承诺链,如下所示:

const findUserInApi = (username) => {
  return findChattersPerRole()
    .then(chattersPerRole => {
      console.log(`${username} should\'ve been added by now...`);
      //console.log(chattersPerRole);
      let wantedUser = find(chattersPerRole, {username});
      if (!wantedUser) {
        console.log(`${wantedUser} wasn't found m8`);
        return Promise.resolve(null);
      }
      console.log('wanteduser is: ', wantedUser);
      getUserByUsername(wantedUser.username)
        .then(foundUser => {
          console.log('founduser is: ', foundUser);
          return Promise.resolve(foundUser);
        });
    });
};

请注意return中添加了return findChattersPerRole().then()

但是,您正在嵌套承诺链。这是一种反模式。另外,如评论中所述,您无需在Promise.resolve()中使用.then(),它会自动应用。您的代码可以重构为以下内容:

const findUserInApi = (username) => {
  return findChattersPerRole()
    .then(chattersPerRole => {
      console.log(`${username} should\'ve been added by now...`);
      //console.log(chattersPerRole);
      return find(chattersPerRole, {username});
    })
    .then(wantedUser => {
      if (wantedUser) {
        console.log('wanteduser is: ', wantedUser);
        return getUserByUsername(wantedUser.username);
      }
      else console.log(`${wantedUser} wasn't found m8`);
    })
    .then(foundUser => {
      if (foundUser) console.log('founduser is: ', foundUser);
      return foundUser;
    });
};