• Gist


    The concept of "Promise"

    Promise is used to asynchronous computations.

    Introduction

    "Synchronize asynchronous methods" is always a hot topic.Here, "Promise" is one way to achieve the goal.

    Promise Model

    Basic Promise Model

    In javascript, it's like:

    // #1 Create a "Promise" object
    const testPromise = new Promise( (resolve, reject) => {
      // resolve("parameters") or reject("parameters")
      // example 1: setTimeout(resolve, 1000, 'parameters')
      // example 2: setTimeout(reject, 1000, 'parameters')
    } )
    
    testPromise.then( value => {
        // #2 Monitor the state of "Promise", if state is "fulfilled"
    },  value => {
        // #2 Monitor the state of "Promise", if state is "rejected"
    })
    
    

    Chaining promise model

    const testPromise = new Promise( (resolve, reject) => {
      // set the state of "Promise" to "fulfilled"
      resolve()
    } )
    
    testPromise
        .then( value => {
            // Continue to create "Promise"
            return new Promise( (resolve, reject) => {
                resolve()
            } )
        }, value => {
        })
        .then( value => {
            // Continue to create "Promise"
            return new Promise( (resolve, reject) => {
            resolve('parameters')
            } )
        }, value => {
        })
        .then( value => {
            console.log(value)  // output: 'paramaters'
        }, value => {
        })
    

    Grammar

    Initialize

    Promise constructor

    Chain

    Promise.prototype.then()

    Catch rejected reason

    Promise.prototype.catch()

    Resolve or reject parameters directly

    Promise.resolve()
    Promise.reject()

    Queue

    Promise.all()

    Apply fastest promise

    Promise.race

    Conclusion

    There must be lots of ways to synchronize asynchronous methods, however, it's more convenient if a standard emerges so we can build robust program more easily.Obviously, promise is an ideal standard.

  • 相关阅读:
    浏览器渲染机制
    isEmpty 和 isBlank 的用法区别
    Mybatis-plus
    Java8的JVM内存结构
    【面试题】关于线程交替的面试题
    java中的final的作用
    线程池
    六种实现单例模式的方法
    SQL优化常用方法
    HTML学习笔记
  • 原文地址:https://www.cnblogs.com/terrysu/p/7103083.html
Copyright © 2020-2023  润新知