Promise学习前篇

150 阅读2分钟

一.实例对象和函数对象

  1. 实例对象:new函数产生的对象,称为实例对象,简称为对象

  2. 函数对象:将函数作为对象使用时,简称为函数对象

    function Fn(){} //Fn函数
    const fn = new Fn() 
    //Fn是构造函数,fn是实例对象
    Fn.prototype 
    //Fn是函数对象,将函数通过.操作属性和方法和作为对象使用
    Fn.bind({}) 
    //bind定义在所有函数对象的原型上
    ${'#test'}  //jquery函数
    $.get('/test')  //jquery作为函数对象.
    

二.两种类型的回调函数

  1. 同步回调

    • 理解:立即执行,完全执行完毕才结束,不会放入回调队列中

    • 例子:数组遍历相关的回调函数

      const arr = [1,3,5]
      arr.forEach(v=>{  //遍历回调,同步回调函数
        console.log(v);
      })
      console.log('forEach()之后')
      
  2. 异步回调

    • 理解:不会立即执行,会放入回调队列中将来执行

    • 例子:定时器回调 / ajax回调 / Promise的成功|失败的回调

      setTimeout(()=>{ 
      //异步回调函数,会放入队列中将来执行
        console.log('time callback()')
      },0)
      console.log('setTimeout() 之前')
      

三.error的处理

  1. 错误的类型

        Error:所有的错误类型
        常见的内置错误
          //ReferenceError 引用的变量不存在
          console.log(a)  
          //ReferenceError: a is not defined
          //没有捕获error,下面的代码不会执行
          //TypeError 数据类型不正确
          let b = null;
          cosole.log(b.xxx)  
          //TypeError:Cannot read propert 'xxx' of ndefined
          b.xxx(); 
          /TypeError:b.xxx is not a function
          //RangeError :数据值不在其所允许的类型
          function fn(){
            fn();
          }
         fn() //RangeError:Maximun call stack size exceeded
        //SytaxError : 语法错误
        const c = """"; //SytaxError:Unexpexted string
    
  2. 错误处理

    //捕获错误:try ... catch ==>程序错误
    try {
      let b = null;
      cosole.log(b.xxx) 
    }catch(error){
      console.log(error.message); //error是对象
    }
    Sources 光标节点查看,类型名称(message),属性(stack)
    //抛出错误:throw error
    function something(){
      if(Date.now()%2===1){
        console.log("当前时间为基数,可以执行")
      }else{ //抛出异常,由调用者处理
        throw new Error("当前时间为偶数,无法执行")
      }
    }
    try { 
    //由捕获接收到的调用者处理异常
      something()
    }catch(error){
      alert(error.message)
    }
    
  3. 错误对象

    message属性:错误相关信息
    stack:函数调用栈记录信息