node.js - 如何在另一个异步中调用异步
问题描述
我正在尝试使用带有在数据库中加密的 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 调用?最佳做法是什么?
解决方案
// 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);
}
});
});
}
提示是,一旦您开始处理异步代码,请尝试以异步方式编写您自己的函数。
推荐阅读
- mysql - 在插入之前触发 MySQL 更新属性
- aws-cdk - AWS CDK - 尝试使用类 aws_cdk.aws_events.RuleTargetInputProperties 添加输入转换器
- python - Tkinter 覆盖文本
- angular - Angular 11-TypeError:无法在“窗口”上执行“获取”:非法调用
- typescript - 在 npm 安装后手动将类型复制到 @types/ 目录
- c# - 无法将 DBNull 与 NULL 列值匹配
- mysql - Docker 提交数据库
- reporting-services - 如何在 SSRS REPORT 的搜索框中搜索多个“值”
- javascript - JavaScript 日期数组到日期范围数组
- karate - 空手道 - $ | 不是字符串 (LIST:STRING) 失败