[英]Clearner way to wait for function to complete before continuing
First I fetch a random quote from a public api. Only AFTER I actually have a quote I want to render the page including that quote.首先,我从公共 api 获取随机报价。只有在我真正有报价之后,我才想呈现包含该报价的页面。
I am a JavaScript newbie so please bear with me if this is a stupid question.我是 JavaScript 新手,如果这是一个愚蠢的问题,请多多包涵。
I was struggling with waiting for the api call to return BEFORE continuing with rendering the page.在继续呈现页面之前,我一直在努力等待 api 调用返回。 I wanted to do the following, but this doesn't work because
res.render
will be called before I have a quote.我想执行以下操作,但这不起作用,因为在我引用之前会调用
res.render
。 (note: I am using Express and Axios) (注意:我使用的是 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 })
})
The only way I figured out to do it is as follows, but I find this really messy.我想出的唯一方法如下,但我发现这真的很乱。 Is there a cleaner way to do this?
有没有更清洁的方法来做到这一点? Or do I always need to put all the lines of code that I want to wait for each other in an async function?
或者我是否总是需要将所有我想要等待的代码行放在异步 function 中?
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()
})
(Note: I realize rendering the page after I successfully get a quote is not ideal either because this means I will not get a page at all if the quote api (for some reason) doesn't work. But for now I just want to know how to do this with the waiting.) (注意:我意识到在成功获得报价后呈现页面也不理想,因为这意味着如果报价 api(出于某种原因)不起作用,我根本不会获得页面。但现在我只想知道如何在等待中做到这一点。)
Heres what you need to do.这是您需要做的。 Make your controller
async
by doing this app.get('/', async (req, res)
通过执行此操作使您的 controller
async
app.get('/', async (req, res)
app.get('/', async (req, res) => {
const quote = await getRandomQuote()
console.log(`${quote.content} - ${quote.author}`) //This prints 'undefined' because 'getRandomQuote' isn't finished yet
res.render('home', { quote })
})
Try this:尝试这个:
getRandomQuote()
.then(quote => {
console.log(`${quote.content} - ${quote.author}`)
res.render('home', { quote })
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.