简体   繁体   English

路线返回等待功能完成

[英]Route returns be await function is complete

In the following code, the route is returning before the array is populated, so the array returns empty. 在下面的代码中,路由在数组填充之前返回,因此数组返回空值。 I know I'm doing something wrong with promises and/or async and await, but I can't figure out what it is. 我知道我在Promise和/或异步等待中做错了事,但是我不知道这是什么。

router.get('/:deckId', auth.required, (req, res) => {
  Deck.findById(req.params.deckId).then(deck => {
    let cardArray = []
    deck.cards.forEach(card => {
      const url = `https://api.scryfall.com/cards/${card.id}`
      getScryFallCard(url).then(a => cardArray.push(a))
    })
    res.json({
      name: deck.name,
      id: deck._id,
      cards: cardArray
    })
  })
})

I have tried making all the function asynchronous and putting await next to the child function. 我试图使所有功能异步,并在子功能旁边放置等待。 I've tried creating a promise, putting await next to that promise, and then returning the response. 我尝试过创建一个承诺,在该承诺旁边等待,然后返回响应。 I've tried using a callback on the mongoose function rather than a Promise. 我试过对猫鼬函数而不是Promise使用回调。 I've tried other combinations of promise, async, await, and callbacks with no success. 我尝试了promise,async,await和callback的其他组合,但均未成功。 What is the correct way to return the response after the array has been populated? 填充数组后返回响应的正确方法是什么?

This is the response I get. 这是我得到的回应。 The cards key should be populated with an array of cards. 卡密钥应填充有一系列卡。

{
    "name": "Dovin",
    "id": "5ca50448232aa920636dd571",
    "cards": []
}
router.get('/:deckId', auth.required, (req, res) => {
  Deck.findById(req.params.deckId).then(async deck => {
    let cardArray = []
    for (let card of deck.cards) {
      const url = `https://api.scryfall.com/cards/${card.id}`
      let a = await getScryFallCard(url)
      cardArray.push(a)
    }
    res.json({
      name: deck.name,
      id: deck._id,
      cards: cardArray
    })
  })
})

You need to call res.json after all code in the loop is executed. 在执行循环中的所有代码之后,您需要调用res.json await makes sure next line is not executed until we get the asynchronous job done. await确保在完成异步作业之前不执行下一行。 So response ( res.json ) is send after all calls are completed inside the loop. 因此,在循环内所有调用完成后,将发送响应( res.json )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM