范围未找到变量

时间:2018-02-12 13:59:19

标签: javascript node.js

有!我一直在尝试在我的代码(totalsoldTickets)上使用两个变量,但它们并没有被总结或显示正确的值。我认为这与范围有关。 console.log()分别返回0[]

class SaleController {

    constructor() {
        this.Sale = require('../models/Sale')
        this.Show = require('../models/Show')
    }

    buyTickets(req, res) {
        const json = req.body

        let soldTickets = []
        let total = 0

        json.tickets.forEach(ticket => {

            for (let i = 0; i < ticket.qty; i++) {

                this.Show.findById(ticket.showId, 'sectors', (err, shows) => {
                    if (err) return res.status(500).json({
                        status: 'failed',
                        message: 'Something happened while finding the show!'
                    })

                    const foundTicket = shows.sectors.find(sector => sector.name === ticket.sector)
                    total += foundTicket.price

                    soldTickets.push({
                        number: this.generateTicketNumber(),
                        showId: ticket.showId,
                        sector: ticket.sector,
                        price: foundTicket.price
                    })
                })

            }

        })

        console.log(total)
        console.log(soldTickets)

        res.json({
            tickets: soldTickets,
            total: total
        })
    }

    generateTicketNumber() {
        return Math.floor(Math.random()*90000) + 10000
    }
}

module.exports = new SaleController()

1 个答案:

答案 0 :(得分:0)

问题是您在回调函数中设置变量。这与范围无关,而是与执行顺序无关。

在使用total或soldTickets变量执行任何操作之前,您需要等待最后一次回调完成。

所以你知道你做的请求数量(ticket.qty)。如果这是最后一个请求,您现在可以在回调函数内部进行检查。如果是,您可以返回两个值。

class SaleController {

    constructor() {
        this.Sale = require('../models/Sale')
        this.Show = require('../models/Show')
    }

    buyTickets(req, res) {
        const json = req.body

        let soldTickets = []
        let total = 0

        json.tickets.forEach(ticket => {

            for (let i = 0; i < ticket.qty; i++) {

                this.Show.findById(ticket.showId, 'sectors', (err, shows) => {
                    if (err) return res.status(500).json({
                        status: 'failed',
                        message: 'Something happened while finding the show!'
                    })

                    const foundTicket = shows.sectors.find(sector => sector.name === ticket.sector)
                    total += foundTicket.price

                    soldTickets.push({
                        number: this.generateTicketNumber(),
                        showId: ticket.showId,
                        sector: ticket.sector,
                        price: foundTicket.price
                    })

                    // If it was the last request
                    if (i === ticket.qty - 1 && json.tickets.indexOf(ticket) === json.tickets.length - 1) {
                      // Log values
                      console.log(total)
                      console.log(soldTickets)

                      // send response
                      res.json({
                        tickets: soldTickets,
                        total: total
                      })
                    }

                })

            }

        })
    }

    generateTicketNumber() {
        return Math.floor(Math.random()*90000) + 10000
    }
}

module.exports = new SaleController()

请注意,此代码未经测试。

当第二个最后一个请求比实际最后一个请求花费更长时间时,可能会遇到一些问题。因此,我建议建立一个计数器来衡量已经回来的请求数量。在最后一次请求之后,它应该响应值。