【问题标题】:Clearner way to wait for function to complete before continuing在继续之前等待功能完成的更简洁的方法
【发布时间】: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) => {之前

标签: javascript async-await


【解决方案1】:

这是您需要做的。通过这样做app.get('/', async (req, res) 来制作你的控制器async

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 })
})

【讨论】:

    【解决方案2】:

    试试这个:

    getRandomQuote()
    .then(quote => {
      console.log(`${quote.content} - ${quote.author}`) 
      res.render('home', { quote })
    });
    

    【讨论】:

    • 行得通!所以 .then 也会自动等待。
    • 是的,它是Promise API 的一部分,如果您在函数中返回Promise 或使用async 声明函数,它就可以工作。
    猜你喜欢
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多