详解Node.js异步迭代器及其使用方法


当前第2页 返回上一页

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

function fetchCatPics({ limit, page, done }) {

  return homebrewFetch(`https://api.thecatapi.com/v1/images/search?limit=${limit}&page=${page}&order=DESC`)

    .then(body => ({ value: body, done }));

}

 

function catPics({ limit }) {

  return {

    [Symbol.asyncIterator]: async function*() {

      let currentPage = 0;

      // 5 页后停止

      while(currentPage < 5) {

        try {

          const cats = await fetchCatPics({ currentPage, limit, done: false });

          console.log(`Fetched ${limit} cats`);

          yield cats;

          currentPage ++;

        } catch(error) {

          console.log('There has been an error fetching all the cats!');

          console.log(error);

        }

      }

    }

  };

}

 

(async function() {

  try {

    for await (let catPicPage of catPics({ limit: 10 })) {

      console.log(catPicPage);

      // 每次请求之间等待 7 秒

      await new Promise(resolve => setTimeout(resolve, 7000));

    }

  } catch(error) {

    console.log(error);

  }

})()

这样,我们就会每隔7秒钟自动取回一整页的喵星人图片。

一种更常见的页面间导航的方法可实现 nextprevious 方法并将它们公开为控件:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

function actualCatPics({ limit }) {

  return {

    [Symbol.asyncIterator]: () => {

      let page = 0;

      return {

        next: function() {

          page++;

          return fetchCatPics({ page, limit, done: false });

        },

        previous: function() {

          if (page > 0) {

            page--;

            return fetchCatPics({ page, limit, done: false });

          }

          return fetchCatPics({ page: 0, limit, done: true });

        }

      }

    }

  };

}

 

try {

    const someCatPics = actualCatPics({ limit: 5 });

    const { next, previous } = someCatPics[Symbol.asyncIterator]();

    next().then(console.log);

    next().then(console.log);

    previous().then(console.log);

} catch(error) {

  console.log(error);

}

如你所见,当要获取数据页面或在程序的 UI 上进行无限滚动之类的操作时,异步迭代器会非常有用。

这些功能在 Chrome 63+、Firefox 57+、Safari 11.1+ 中可用。

你还能想到可以把异步迭代器用在什么地方吗?欢迎在下面留言!

更多编程相关知识,请访问:编程视频!!

以上就是详解Node.js异步迭代器及其使用方法的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

浅谈 node.js 中间件的工作原理

了解nodejs中的事件和事件循环

npm和yarn安装node-sass的问题解决方法介绍

export和export default中的知识点介绍(附示例)

如何从javascript到typescript?

node.js学习之静态资源服务器

javascript、node.js和npm之间有什么关系

了解http事务、node模块化规范

详解使用node.js怎么处理cors

详解node.js中的quic协议

更多相关阅读请进入《node.js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...