zoukankan      html  css  js  c++  java
  • 7.JavaScript-Promise的并行和串行

    Promise 并行

    Promise.all是所有的Promise执行完毕后(reject|resolve)返回一个Promise对象。

    最近在开发一个项目中,需要等接口拿到全部数据后刷新页面,取消loding效果

     1  // 项目中请求接口
     2 function getShowProject(resolve, reject) {
     3     $.ajax({
     4       url: `${api}/rrz/member/showProjectById`,
     5       type: 'get',
     6       data: { appId: appId },
     7       success: function (res) {
     8         if (res.result == 'success') {
     9           gather['listBy'] = res.data;
    10           resolve();
    11         }
    12       }
    13     });
    14   }
    15   function getProjectPic(resolve, reject) {
    16    ...
    17   }
    18   function projectRelation(resolve, reject) {
    19    ...
    20   }
    21   function queryProjectDynamicS(resolve, reject) {
    22    ...
    23   }
    24   function showProjectLoveValue(resolve, reject) {
    25    ...
    26   }
    27   function getAppProjectDonorComment(resolve, reject) {
    28    ...
    29   }
    30   // 等待接口全部请求完成后  刷新页面
    31   var a1 = new Promise(getShowProject);
    32   var a2 = new Promise(getProjectPic);
    33   var a3 = new Promise(projectRelation);
    34   var a4 = new Promise(queryProjectDynamicS);
    35   var a5 = new Promise(showProjectLoveValue);
    36   var a6 = new Promise(getAppProjectDonorComment);
    37   Promise.all([a1, a2, a2, a3, a4, a5, a6]).then(function () {
    38     info = { data: gather }
    39     getDetail();
    40     console.log('loading效果图消失');
    41   })

    Promise 串行

    在项目的实际操作中会用到串行调用方法的情况,实现异步执行,例如
    有三个方法,方法一、方法二、方法三,需要执行完方法一之后执行方法二,执行完方法二之后执行方法三,可以用Promise实现,简单的模拟做法如下:

    function one(){
        console.log(11111);
    }
    
    function two(){
        console.log(22222);
    }
    
    function three(){
        console.log(33333);
    }
    function fiveP(func){
        return new Promise(function(resolve, reject) {
            func();
            resolve();
        });
    }
    
    p.then(fiveP(one))
    .then(fiveP(three))
    .then(fiveP(two))
    .then(function(result) {
        console.log('最后执行' + result);
    });
    // 执行结果 
    // 1111
    // 3333
    // 2222
    // 最后执行
  • 相关阅读:
    html 之input标签height设置问题
    jquery 练习笔记
    JavaScript
    css记录
    python 反射器
    python 之 前端初识 html
    [mysql]修改
    [mysql]约束
    [mysql]select
    python_exercise_能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径
  • 原文地址:https://www.cnblogs.com/xiaole9924/p/11842180.html
Copyright © 2011-2022 走看看