• js的promise用法


            js中的promise是一个异步编程的解决方案,语法层面上他是一个构造函数,名字为Promise()。

            他的作用就是将一个任务task封装为一个Promise类的实例对象,这个对象会将任务自动运行并得到任务结果,而且在得到结果的过程中并不会影响到其他任务的进行。由此实现多个任务的并发进行。

            实现异步的过程被隐藏在Promise类的实现过程中,我们只需要将任务交给Promise,Promise给我们一个instance,之后通过instance去拿任务结果就可以了。我们可以创建多个Promise类的实例instance。

            下面将介绍Promise用法的一般代码写法。

    目录

    1,Promise构造函数参数介绍

    2,Promise实例对象的then()方法

    3,异步加载图片的例子

    4,Ajax实操


    1,Promise构造函数参数介绍

            Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。resolve和reject是两个函数,由JavaScript引擎提供,不用自己部署。

    1. //resolve, reject名称不能修改
    2. const promise = new Promise(function(resolve, reject) {
    3. // ...some code
    4. if ( /*异步操作成功,执行resolve方法,目的一般是将某些结果返回出去*/ ) {
    5. resolve(value);
    6. } else {
    7. /*异步操作失败,执行reject方法,目的一般也是将某些结果返回出去*/
    8. reject(error);
    9. }
    10. });

    2,Promise实例对象的then()方法

            Promise 实例生成以后,可以用then方法分别指定resolved状态和rejected 状态的回调函数。也就是对返回的任务结果进行处理。

    1. promise.then(resolved = function(value) {
    2. // success,对返回的结果value进行处理
    3. },
    4. rejected = function(error) {
    5. //failure,直接把错误类型报给用户
    6. });

    3,异步加载图片的例子

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>异步加载图片title>
    8. head>
    9. <body>
    10. <div id="box">div>
    11. <script>
    12. box = document.getElementById('box');
    13. function loadImageAsync(url) {
    14. /*创建一个image资源对象,因为要网络请求,比较消耗时间***********************/
    15. function task(resolve, reject) {
    16. const image = new Image();
    17. image.src = url;
    18. //onload等于true
    19. image.onload = function() {
    20. resolve(image);
    21. };
    22. //onerror等于false
    23. image.onerror = function() {
    24. reject(new Error(' could not load image at ' + url));
    25. };
    26. }
    27. return new Promise(task);
    28. }
    29. promise = loadImageAsync('https://pan.baidu.com/box-static/disk-theme/theme/white/img/logo@2x.png');
    30. promise.then(
    31. function(data) {
    32. box.appendChild(data);
    33. },
    34. function(error) {
    35. box.innerHTML = '图片加载失败';
    36. console.log(error);
    37. }
    38. )
    39. script>
    40. body>
    41. html>

    4,Ajax实操

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>ajax实操title>
    8. head>
    9. <body>
    10. <div id="box">div>
    11. <script>
    12. box = document.getElementById('box');
    13. function GETJSON(url) {
    14. /*************************************************************/
    15. function ajaxTask(resolve, reject) {
    16. const handler = function() {
    17. if (this.readystate !== 4) {
    18. return;
    19. }
    20. if (this.status === 200) {
    21. resolve(this.response);
    22. } else {
    23. reject(new Error(this.statusText));
    24. }
    25. };
    26. const client = new XMLHttpRequest();
    27. client.open("GET", url);
    28. client.onreadystatechange = handler;
    29. client.responseType = "json";
    30. client.setRequestHeader("Access-Control-Allow-Origin", "*");
    31. client.send();
    32. }
    33. /*************************************************************/
    34. return new Promise(ajaxTask);
    35. };
    36. /*************************************************************/
    37. promise = GETJSON("https://www.hupu.com/home/v1/news?pageNo=4&pageSize=50");//出现ajax无法跨域的问题,目前还不会解决
    38. promise.then(
    39. function(data) {
    40. console.log(data);;
    41. },
    42. function(error) {
    43. box.innerHTML = '加载失败';
    44. console.log(error);
    45. }
    46. )
    47. script>
    48. body>
    49. html>
  • 相关阅读:
    cube-studio配置镜像仓库并允许
    MyBatis调用MySQL存储过程实例
    Docker使用数据卷自定义镜像Dockerfile
    Unity中Shader光照模型Blinn-Phong原理及实现
    用人工智能压缩图像的尝试2
    HCIP---VLAN
    计算机网络(文章链接汇总)
    Java 线程通信之线程安全问题
    springboot+Vue.js+Elementui大学生就业信息网站管理系统java项目推荐
    wy的leetcode刷题记录_Day49
  • 原文地址:https://blog.csdn.net/weixin_44992737/article/details/126056971