带你玩转 JavaScript ES6 (七) - 异步

带你玩转 JavaScript ES6 (七) – 异步

本文同步
带你玩转 JavaScript ES6 (七) – 异步,转载请申明出处。

本章我们将进修 ES6 中的 Promise(异步) 相干学问,相识怎样运用 Promise 对象建立异步递次

一、引见

Promise 对象经由过程 new Promise(executor) 实例化建立,能够让递次进入一个异步的实行中,完成耗时的操纵处置惩罚。

二、语法

2.1 实例化

语法:new Promise((resole, reject) => {})

Promise 类吸收带有两个匿名函数作为参数的匿名函数,个中 resolve 示意胜利处置惩罚函数,reject 示意失利处置惩罚函数

let promise = new Promise((resole, reject) => {
    console.log('main')
    setTimeout(() => {
        resole('run async')
    }, 1500)
})
 

2.2 异步胜利实行处置惩罚要领

经由过程 Promise 对象的 then 要领绑定 resolve处置惩罚要领,能够经由过程链式操纵绑定多个用于 resolve 的处置惩罚要领


let promise = new Promise((resole, reject) => {
    console.log('main')
    setTimeout(() => {
        resole('run async')
    }, 1500)
})

promise.then((msg) => {
    console.log(msg);
})

上面示例会先打印输出 mian,之后过 1.5 s 会打印输出 run async 到控制台。为了演示异步实行,如今对上例稍作调解:

let promise = new Promise((resole, reject) => {
    resole('run async')
    console.log('main')
})

promise.then((msg) => {
    console.log(msg);
})

我们首先将 resolve(‘run async’) 挪用移至 console.log(‘main’) 之前。

如果是同步挪用根据实行递次,会先输出 run async 再输出 main,但状况相反。申明 resolve 处置惩罚要领被异步实行了。

2.3 异步失利实行处置惩罚要领

经由过程运用 Promise 对象的 catch 要领绑定 reject 处置惩罚要领。

let promise = new Promise((resole, reject) => {
    //resole('run async')
    reject('run async error')
    console.log('main')
})

promise.then((msg) => {
    throw new Error('error')
    console.log(msg);

}).catch(() => {
    console.log('error')
})

三、 Promise 生命周期

一个 Promise有以下几种状况:

  • pending: 初始状况,既不是胜利,也不是失利状况。
  • fulfilled: 意味着操纵胜利完成。
  • rejected: 意味着操纵失利。

pending 状况的 Promise 对象能够触发fulfilled 状况并通报一个值给响应的状况处置惩罚要领,也能够触发失利状况(rejected)并通报失利信息。

当个中任一种状况出现时,Promise 对象的 then 要领绑定的处置惩罚要领(handlers )就会被挪用(then要领包括两个参数:onfulfilled 和 onrejected,它们都是 Function 范例。当Promise状况为fulfilled时,挪用 then 的 onfulfilled 要领,当Promise状况为rejected时,挪用 then 的 onrejected 要领, 所以在异步操纵的完成和绑定处置惩罚要领之间不存在合作)。

《带你玩转 JavaScript ES6 (七) - 异步》

注: Promise 生命周期相干内容援用自 Promise

四、运用 Promise 和 XHR 异步加载图片

这是 MDN 官方给出的示例,JavaScript 部份的代码以下

  function imgLoad(url) {
    // Create new promise with the Promise() constructor;
    // This has as its argument a function
    // with two parameters, resolve and reject
    return new Promise(function(resolve, reject) {
      // Standard XHR to load an image
      var request = new XMLHttpRequest();
      request.open('GET', url);
      request.responseType = 'blob';
      // When the request loads, check whether it was successful
      request.onload = function() {
        if (request.status === 200) {
        // If successful, resolve the promise by passing back the request response
          resolve(request.response);
        } else {
        // If it fails, reject the promise with a error message
          reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
        }
      };
      request.onerror = function() {
      // Also deal with the case when the entire request fails to begin with
      // This is probably a network error, so reject the promise with an appropriate message
          reject(Error('There was a network error.'));
      };
      // Send the request
      request.send();
    });
  }
  // Get a reference to the body element, and create a new image object
  var body = document.querySelector('body');
  var myImage = new Image();
  // Call the function with the URL we want to load, but then chain the
  // promise then() method on to the end of it. This contains two callbacks
  imgLoad('myLittleVader.jpg').then(function(response) {
    // The first runs when the promise resolves, with the request.response
    // specified within the resolve() method.
    var imageURL = window.URL.createObjectURL(response);
    myImage.src = imageURL;
    body.appendChild(myImage);
    // The second runs when the promise
    // is rejected, and logs the Error specified with the reject() method.
  }, function(Error) {
    console.log(Error);
  });
  
    原文作者:柳公子
    原文地址: https://segmentfault.com/a/1190000013171493
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞