我的迭代器在迭代过程中不会中断

问题描述 投票:0回答:1

我编写了一个简单的迭代器,我想在满足特定条件时中断它。但是,当条件满足时,它不会这样做。下面是迭代器和骨架类,展示了 searchByDate 函数是如何实现和调用的。问题是,即使进入循环并且始终打印值 15(这是 Order 搜索的限制),它也不会中断。当它找到当前订单时,它应该会中断,但即使找到了订单,它也不会中断

        import { plusDays} from "./dateUtils.ts";

        import {
            isEmpty,
        } from "./collection-utils";

        export class DateIterator {
            date: Date

            limit = 15
            currentCount = 0
            constructor(date:Date) {
                this.date = date
            }


            next() {
                if (this.currentCount <= this.limit) {
                    const search = plusDays(this.date.toDateString(),1)
                    console.warn({currentNumberOfDays: this.currentCount}, 'Number of days iterated')
                    this.currentCount++
                    return { done: false, value: search}
                }
                else
                {
                    return {
                        done: true,
                        value: this.date
                    }
                }
            }
        }

        export class DateIncrementor {
            initDate: Date
            constructor(initialDate:Date) {
                this.initDate = initialDate
            }

            [Symbol.iterator]() {
                return new DateIterator(this.initDate);
            }
        }
        
        class Order {
            //...
            
            orderItems = ()
        }
        
        class OrderService {
            getOrdersForDate = async(date:string) =>{
                return new Order()
            }

            isCurrentOrder = (orderDetails:Order) =>{
                return true
            }
        }

        const searchByDate = async(date:Date) => {
            const orderService = new OrderService()
            const  nextDaySearchIterator =  new DateIncrementor(date)
            let count = 0
            let result = {} as Order
            for await (let currentDate of new DateIncrementor(date) ){
                count+=1
                if(date){
                    const orderDetails:Order = await orderService.getOrdersForDate(currentDate)
                    if(orderService.isCurrentOrder(orderDetails)) {
                        if(!isEmpty(orderDetails.orderItems)){
                            result = orderDetails
                            break
                        }
                    }
                }
            }
            console.log('Number of executions of iterator',count)
            return result? result : null
        }
javascript typescript iterator
1个回答
0
投票

我解决了这个问题。我写了一个 AsyncIterator 正确解决了这个问题

© www.soinside.com 2019 - 2024. All rights reserved.