• xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!


    js 深入原理讲解系列-Promise

    能看懂这一题你就掌握了 js Promise 的核心原理

    不要专业的术语,说人话,讲明白!

    Q: 输出下面 console.log 的正确的顺序?

    const log = console.log;
    
    
    

    A:

    
    

    Promise

    不可逆状态: pending => fullfilled, pending => rejected

    Promise.resolve()
    Promise.reject()

    executor 执行器

    thenable 包含 then 的对象,会立即执行 then ?
    then

    Promise.all
    Promise.allSettled
    Promise.any
    Promise.race
    Promise.catch 语法糖 new Promise(null, (err) => reject(err))
    Promise.finally 兜底

    Promise.try ❓too new for now

    try...catch

    Promise

    let promise = new Promise((resolve, reject) => resolve(`value`));
    // let promise = new Promise((resolve, reject) => reject(`error`));
    
    promise.then(function(value) {
      // success, fullfiled ✅ / (resolved ❌)
      console.log(`OK =`, value);
    }, function(error) {
      // failure, rejected
      console.log(`Error =`, error);
    });
    // OK = value
    
    
    

    promise = new Promise((resolve, reject) => {
      throw new Error(`promise error!`);
    });
    
    promise.then(function(value) {
      // success, fullfiled ✅ / (resolved ❌)
      console.log(`OK =`, value);
    }, function(error) {
      // failure, rejected
      console.log(`Error =`, error);
    }).catch(err => {
      console.log(`Catch Error =`, err);
    });
    // Error = Error: promise error!
    
    

    thenable

    
    const log = console.log;
    
    const thenableOK = {
      then: function(resolve, reject) {
        log(`thenable ✅`);
        resolve(2020);
      },
    };
    
    Promise.resolve(thenableOK).then(function(value) {
      log(`value =`, value);
      // 2020
    }, function(error) {
      log(`error =`, error);
    });
    
    // thenable ✅
    // value = 2020
    // Promise {<fulfilled>: undefined}
    
    const thenableError = {
      then: function(resolve, reject) {
        log(`thenable ❌`);
        reject(2020);
      }
    };
    
    Promise.resolve(thenableError).then(function(value) {
      log(`value =`, value);
    }, function(error) {
      log(`error =`, error);
    });
    
    // thenable
    // error = 2020
    // Promise {<fulfilled>: undefined}
    
    
    

    refs

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise



    ©xgqfrms 2012-2020

    www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


  • 相关阅读:
    希尔排序
    基数排序
    spring8——AOP之Bean的自动代理生成器
    spring7——AOP之通知和顾问
    spring6——AOP的编程术语
    spring5——Aop的实现原理(动态代理)
    spring4——IOC之基于注解的依赖注入(DI )
    spring3——IOC之基于XML的依赖注入(DI )
    spring2——IOC之Bean的装配
    spring1——IOC之原理
  • 原文地址:https://www.cnblogs.com/xgqfrms/p/14025959.html
Copyright © 2020-2023  润新知