美文网首页
避免callback金字塔——promise

避免callback金字塔——promise

作者: meteornnnight | 来源:发表于2019-08-12 12:47 被阅读0次

    loadScript函数

    有这么一个应用场景:
    我们想要动态地加载一个js脚本,然后调用脚本中的某个函数。所以,这其实抽象为,我们需要等待一个异步请求结果,然后做一些操作。

    function loadScript(src,callback){
      let script=document.creatElement('script');
      script.src=src;
      script.onload=()=>{
        callback(script);
      }
      document.head.appendChild(script);
    }
    

    我们可以用上述的callback机制这么来写。这么写当然没有问题,那么如果我们想要在第一个脚本加载完成之后,去加载第二个脚本,我们就需要在callback里面做这件事,那么代码就会变成这样:

    loadScript('/src/index.js', (script)=>{
      console.log('cool, the first script from '+script.src+' is loaded!');
      loadScript('/src/index2.js', (script)=>{
        console.log('now the second script from '+script.src+' is loaded.');
      }
    });
    

    这样的写法会出现callback金字塔的代码结构。所以我们提出让promise来解决以上的应用场景。
    上述场景如果用promise机制来写的话,语法会更加符合逻辑和规律。

    Promise--executor

    new Promise((resolve,reject)=>{
    //do some stuff
    resolve('done');
    //or
    reject(new Error('error message'));
    })
    

    生成一个新的Promise对象,会立刻执行executor函数。
    promise 对象有内部属性:

    • state —— 最初是 “pending”,然后被改为 “fulfilled” 或 “rejected”,
    • result —— 一个任意值,最初是 undefined。

    当 executor 完成任务时,应调用下列之一:

    • resolve(value) —— 说明任务已经完成:
      将 state 设置为 "fulfilled",sets result to value。
    • reject(error) —— 表明有错误发生:
      将 state 设置为 "rejected",将 result 设置为 error。

    我们经常会在promise中发送异步请求,然后去调用resolve或者reject,实际上,在executor中立即调用它们也是可以的。

    //常见用法
    new Promise(()=>{
      console.log(resolve);
      console.log(reject);
      setTimeout(()=>{
        resolve('done');
      },1000);
    );
    

    Promise--then, catch

    promise完成之后,either fulfilled or rejected, 我们可以在promise提供的.then, .catch函数中做进一步的操作。
    On settled promises then runs immediately

    //when it is resolved
    promise.then(
    (result)=>console.log(result)
    )
    // when it is rejected
    promise.catch(
    (error)=>console.log(error.message)
    )
    

    用promise改写loadScript()

    function loadScript(src){
      return new Promise((resolve,reject)=>{
        const script=document.createElement('script');
        script.src=src;
        document.head.appendChild(script);
        script.onload=()=>{resolve(script)};
        script.onerror=()=>{reject(new Errror('the script is failed to load '+src))}
      })
    }
    let promise1=loadScript('./index.js');
    promise1.then(
      (result)=>{console.log(`${result.src} is loaded!`)},
      (error)=>{console.log(error.message)}
    )
    

    Promise chain

    new Promise(function(resolve, reject) {
    
      setTimeout(() => resolve(1), 1000); // (*)
    
    }).then(function(result) { // (**)
    
      alert(result); // 1
      return result * 2;
    
    }).then(function(result) { // (***)
    
      alert(result); // 2
      return result * 2;
    
    }).then(function(result) {
    
      alert(result); // 4
      return result * 2;
    
    });
    

    要看懂这段代码,只需要理解:
    promise.then((value)=>return 2*value)会返回一个新的promise, 状态为fulfilled, value为2, 所以我们可以连续调用.then(),形成promise chain.

    return Promise

    new Promise(function(resolve, reject) {
    
      setTimeout(() => resolve(1), 1000);
    
    }).then(function(result) {
    
      alert(result); // 1
    
      return new Promise((resolve, reject) => { // (*)
        setTimeout(() => resolve(result * 2), 1000);
      });
    
    }).then(function(result) { // (**)
    
      alert(result); // 2
    
      return new Promise((resolve, reject) => {
        setTimeout(() => resolve(result * 2), 1000);
      });
    
    }).then(function(result) {
    
      alert(result); // 4
    
    });
    

    (*)处返回的是一个新的promise,js引擎会一直等到这个新的promise resolved之后,再去执行(**)处的.then函数。
    返回 promises 允许我们建立异步动作链
    应用场景:顺序加载脚本1,脚本2,脚本3,然后调用这些脚本里面的函数(用promise chain来轻松实现)

    function loadScript(src){
      return new Promise((resolve,reject)=>{
          const script=document.createElement('script');
          script.src=src;
          script.onload=()=>resolve(script);
          script.onerror=()=>reject(new Error(src+ 'failed.'));
          document.head.appendChild(script);
        }
      )
    }
    loadScript('./index1.js')
    .then(script=>loadScript('./index2.js'))
    .then(script=>loadScript('./index3.js'))
    .then(()=>{
        one();
        two();
        three();
    })
    

    相关文章

      网友评论

          本文标题:避免callback金字塔——promise

          本文链接:https://www.haomeiwen.com/subject/xylhjctx.html