博客
关于我
promise和generator的应用区别
阅读量:338 次
发布时间:2019-03-04

本文共 698 字,大约阅读时间需要 2 分钟。

Promise和Generator都是处理异步操作的工具,但它们在适用场景上有一些差异。以下是对两者的详细比较分析:

Promise适合在一次读取多个固定格式的数据。这种工具在处理简单的数据读取任务时非常高效。例如,在需要一次性读取多个文件或API数据时,Promise能够提供一个简洁的方式来处理这些操作。

相比之下,Generator则更适合处理具有逻辑性的数据。通过使用Generator,我们可以在读取数据的过程中自然地嵌入业务逻辑,使得代码更加简洁易懂。例如,在处理需要分批读取或根据特定条件筛选数据的场景中,Generator能够提供更灵活的解决方案。

以下是具体的示例对比:

  • 普通回调模式

    在普通回调模式下,代码结构通常较为复杂,难以管理多个并发的操作。例如,在读取多个文件时,传统的回调方式可能会导致代码难以管理和扩展。

  • 带逻辑的Promise模式

    当涉及复杂的逻辑判断时,Promise的代码结构可能会显得更加复杂。例如,在读取数据时需要根据特定条件筛选或处理数据时,Promise可能需要通过链式调用和多个then方法来实现,这种模式虽然可行,但相比Generator可能显得更加繁琐。

  • 带逻辑的Generator模式

    Generator模式通过将逻辑嵌入到生成器函数中,能够更自然地处理复杂的数据读取任务。例如,在读取数据时,可以通过生成器函数逐步处理和生成数据,同时嵌入业务逻辑,使得代码更加简洁和易于维护。

  • 综上所述:Promise适合处理一次性读取固定格式的数据,而Generator则更适合处理具有复杂逻辑的数据读取任务。选择哪种工具都需要根据具体的业务需求来决定。

    转载地址:http://dxde.baihongyu.com/

    你可能感兴趣的文章
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>