我正在尝试创建两个函数,一个函数需要两个星期,而另一个函数会在我要显示星期的地方创建提示,这是我尝试过的:
let weeks = {};
async function getWeeks() {
await sql.open('./weeks.db');
sql.get(`SELECT * FROM weeks WHERE id = "1"`).then(row => {
weeks.firstWeek = row.week;
}).catch(console.error);
sql.get(`SELECT * FROM weeks WHERE id = "2"`).then(row => {
weeks.secondWeek = row.week;
}).catch(console.error);
sql.close();
}
await getWeeks().then(async function() {
makeEdits();
});
async function makeEdits() {
message.channel.send(new Discord.RichEmbed().setTitle(`Which week do you want?`).setDescription(` for **${weeks.firstWeek}**.\n for **${weeks.secondWeek}**.`)).then(async function(message) {
// Both values are undefined here however I can use them deeper down into the function
我试图等待一个功能,然后启动另一个功能,但是它没有按预期工作,我该怎么办?
答案 0 :(得分:3)
您还必须await
个sql.get
调用,并且可以将.then
重构为await
来提高可读性:
async function getWeeks() {
const weeks = {}; // local scope helps to prevent racing errors
await sql.open('./weeks.db');
try {
const row = await sql.get(`SELECT * FROM weeks WHERE id = "1"`);
weeks.firstWeek = row.week;
} catch(error) { console.error(error); }
try {
const row = await sql.get(`SELECT * FROM weeks WHERE id = "2"`);
weeks.secondWeek = row.week;
} catch(error) { console.error(error); }
sql.close();
return weeks;
}
function makeEdits(weeks) { /*...*/ }
makeEdits(await getWeeks());