简体   繁体   English

如何在 Node js 中添加延迟加载?

[英]How to add Lazy loading in Node js?

const posts = await Post.find().populate("receiver").populate("author")
        try {
            res.json({
                status: true,
                message: 'All posts fetched',
                data: posts.reverse()
            })

This is my code that sending all posts to frontend.这是我将所有帖子发送到前端的代码。 But I want add lazy loading on backend.但我想在后端添加延迟加载。 Backend must not send all the data at one go.. calling 1000 feed posts after sometime interval.后端不能一次性发送所有数据.. 在某个时间间隔后调用 1000 个提要帖子。 The data will be too large to call via api.数据太大,无法通过 api 调用。

First thing i see: Why didnt you put your await inside the try / catch block?我看到的第一件事:你为什么不把你的await放在try / catch块中?

You can use skip and limit您可以使用skiplimit

I like to do it like this:我喜欢这样做:

    let page = req.body.page - 1;
    let postAmount = 10;
    try {
        const posts = await Post.find().populate("receiver").populate("author").limit(postAmount).skip(postAmount * page)
        res.json({
            status: true,
            message: 'All posts fetched',
            data: posts.reverse()
        })

Depending on if you use GET or POST you will need to send additional page to your API.根据您是使用 GET 还是 POST,您将需要向您的 API 发送额外的page

On page 1 you will see 10 posts.在第 1 页,您将看到 10 个帖子。 At skip you have 10 multiply by 1 that is 10 but you dont want to skip 10 posts on your first fetch.在跳过时,您有 10 个乘以 1,即 10,但您不想在第一次获取时跳过 10 个帖子。 So you need to subscract -1 to have 10 multiply by 0 is 0 so you skip 0 at your first fetch.因此,您需要减去-1才能使 10 乘以 0 为 0,因此您在第一次提取时跳过 0。

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

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