Skip to content

12Promise对象

12.1概念

主要解决异步回调问题特点:1.对象的状态不受外界的影响。2.一旦状态改变,不会再变,任何时候都可以得到结果。缺点:1.无法取消。2.如果不设置回调函数,Promise内部抛出错误,不会反应到外部。3.当处于padding状态时无法得知目前进展到哪一个阶段。

12.2基本使用

Promise作为构造函数需要用new来实例化,Promise接收一个函数作为参数,该函数有两个参数resolve和reject。实例化后有then方法,该方法接收两个函数作为参数。

let p = new Promise(function(resolve,reject){
    if(true) {
        resolve(val)
    }else{
        reject(err)
    }
})

p.then(function(val){},function(err){}) //不建议
p.then(function(val){}).catch(function(err){})

13Iterator 指针对象每次调用返回一个状态

function fn(arr=[]) {
    let nextIndex = 0;
    return {
        next: function(){
            return nextIndex<arr.length? {value: arr[nextIndex++],done: false} : {value: undefined,done: true}
        }
    }
}
let a = fn([1,2,3])
console.log(a.next())
console.log(a.next())
console.log(a.next())
console.log(a.next())