资讯专栏INFORMATION COLUMN

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

he_xd / 3037人阅读

摘要:说明处理方法被异步执行了。意味着操作成功完成。状态的对象可能触发状态并传递一个值给相应的状态处理方法,也可能触发失败状态并传递失败信息。注生命周期相关内容引用自四使用和异步加载图片这是官方给出的示例,部分的代码如下

带你玩转 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 方法, 所以在异步操作的完成和绑定处理方法之间不存在竞争)。

注: 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://www.ucloud.cn/yun/107271.html

相关文章

  • 带你玩转 JavaScript ES6 (六) - Map 映射

    摘要:初始化申明一个设置和获取值使用设置新值或更新值申明设置值张三丰张三丰重复设置值如果键值存在则新值替换旧值张三丰使用获取值,如果获取的不存在返回分别获取判断是否存在使用判断给定是否存在映射内。 本文同步带你入门 带你玩转 JavaScript ES6 (六) - Map 映射,转载请注明出处。 本章我们讲学习 ES6 中的 Map(映射)。上一章节我们学习了 [Set(集合)]()的相关...

    acrazing 评论0 收藏0
  • 带你玩转css3的3D!

    摘要:透视即是以现实的视角来看屏幕上的事物,从而展现的效果。旋转则不再是平面上的旋转,而是三维坐标系的旋转,就包括轴,轴,轴旋转。必须与属性一同使用,而且只影响转换元素。可自由转载引用,但需署名作者且注明文章出处。 showImg(https://segmentfault.com/img/bVzJoZ); 话不多说,先上demo 酷炫css3走马灯/正方体动画: https://bupt-...

    Panda 评论0 收藏0
  • 带你玩转css3的3D!

    摘要:透视即是以现实的视角来看屏幕上的事物,从而展现的效果。旋转则不再是平面上的旋转,而是三维坐标系的旋转,就包括轴,轴,轴旋转。必须与属性一同使用,而且只影响转换元素。可自由转载引用,但需署名作者且注明文章出处。 showImg(https://segmentfault.com/img/bVzJoZ); 话不多说,先上demo 酷炫css3走马灯/正方体动画: https://bupt-...

    archieyang 评论0 收藏0
  • 带你玩转Postman的集合

    摘要:选择选项,可以添加名称和描述的数据,以便其他用户了解你的相关信息,如图创建一个新集合。如果用户正在处理一些特定的集合,可以单击图标将集合置顶,如图过滤集合。 集合...

    Bowman_han 评论0 收藏0
  • 老司机【分享】带你玩转阿里云服务器

    摘要:阿里云是国内云服务器市场的龙头,性价比高,速度快又安全,是站长建站首选的云服务器之一。作为一个老司机,福利吧也和大家分享一下我的阿里云推广经验,教大家如何免费推广云大使。阿里云是国内云服务器市场的龙头,性价比高,速度快又安全,是站长建站首选的云服务器之一。福利吧使用的也是阿里云服务器,是折腾了很多次网站搬家后,才选择了阿里云。身边好几个站长最后都殊途同归,用了阿里云,可见阿里云服务器性能确实...

    banana_pi 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<