【发布时间】:2022-02-13 19:22:05
【问题描述】:
首先,我从公共 api 中获取随机报价。只有在我真正有报价之后,我才想呈现包含该报价的页面。
我是 JavaScript 新手,如果这是一个愚蠢的问题,请多多包涵。
在继续渲染页面之前,我一直在努力等待 api 调用返回。
我想做以下事情,但这不起作用,因为res.render 将在我得到报价之前被调用。 (注意:我使用的是 Express 和 Axios)
async function getRandomQuote() {
try {
const res = await axios.get("https://api.quotable.io/random?tags=famous-quotes")
console.log(`${res.data.content} - ${res.data.author}`) //This prints fine
return res.data
} catch(e) {
console.log('error', e)
}
}
app.get('/', (req, res) => {
const quote = getRandomQuote()
console.log(`${quote.content} - ${quote.author}`) //This prints 'undefined' because 'getRandomQuote' isn't finished yet
res.render('home', { quote })
})
我想出的唯一方法如下,但我觉得这真的很乱。 有没有更清洁的方法来做到这一点?还是我总是需要将所有我想互相等待的代码行放在一个异步函数中?
async function getRandomQuote() {
try {
const res = await axios.get("https://api.quotable.io/random?tags=famous-quotes")
console.log(`${res.data.content} - ${res.data.author}`) //This prints fine
return res.data
} catch(e) {
console.log('error', e)
}
}
app.get('/', (req, res) => {
const getQuoteAndRender = async() => {
const quote = await getRandomQuote()
console.log(`${quote.content} - ${quote.author}`) //This prints only if I wrap everything in yet another aync function, otherwise it will not wait for 'getRandomQuote' to complete
res.render('home', { quote })
}
getQuoteAndRender()
})
(注意:我意识到在成功获得报价后渲染页面也不理想,因为这意味着如果报价 api(由于某种原因)不起作用,我将根本无法获得页面。但现在我只是想知道如何在等待中做到这一点。)
【问题讨论】:
-
把
async放在(req, res) => {之前