首页 > 解决方案 > 如何在另一个异步中调用异步

问题描述

我正在尝试使用带有在数据库中加密的 accessToken 的 API 获取一些数据,我正在获取它然后解密,因此我可以使用它来进行 API 调用,如下所示:

async function getUserGuilds(discord_id) {

//Get Token
const tokenQuery = 'SELECT e_accesstoken FROM users WHERE discord_id = $1';
const discordID = [discord_id];
db.query(tokenQuery, discordID, (err, res) => {
    if (err) {
        console.log(err);
    } else if (!err) {
        const encryptedAccessToken = res.rows[0].e_accesstoken
        const decrypted = decrypt(encryptedAccessToken);
        const accessToken = decrypted.toString(CryptoJS.enc.Utf8);
    }
})

//Call the API after getting the token
const response = await fetch(`${DISCORD_API}/users/@me/guilds`, {
    method: 'GET',
    headers: {
        Authorization: `Bearer ${accessToken}`
    }
});
  return response.json();
}

如您所见,accessToken 在范围之外,我如何访问它并将其用于 API 调用?最佳做法是什么?

标签: node.jsnode-postgres

解决方案


// Since you are using async keywork, this function automatically returns
// a Promise, therefore you will need to handle it with a .then() or await
// in order to get the result.
async function getUserGuilds(discord_id) {
  return new Promise((resolve, reject) => {
    //Get Token
    const tokenQuery = 'SELECT e_accesstoken FROM users WHERE discord_id = $1';
    const discordID = [discord_id];

    db.query(tokenQuery, discordID, async (err, res) => {
      if (err) {
        console.log(err);
        // Rejecting the promise error here will stop the execution, therefore you will not need to
        // add an else statement
        return reject(error);
      }


      const encryptedAccessToken = res.rows[0].e_accesstoken
      const decrypted = decrypt(encryptedAccessToken);
      const accessToken = decrypted.toString(CryptoJS.enc.Utf8);

      // Always wrap async operations with try/catch because they will fail
      // at some point, therefore your code must be prepared to handle it
      try {
        //Call the API after getting the token
        const response = await fetch(`${DISCORD_API}/users/@me/guilds`, {
          method: 'GET',
          headers: { Authorization: `Bearer ${accessToken}` }
        });

        resolve(response.json());
      } catch (error) {
        reject(error);
      }  
    });
  });
}

提示是,一旦您开始处理异步代码,请尝试以异步方式编写您自己的函数。


推荐阅读