zoukankan      html  css  js  c++  java
  • promise理解

    理解图: 以下promise 使用了链式调用的方式 传入一个成功 与失败的函数作为参数使用

     1 API实现: 
     2 //立即执行 简单实例
     3 let promise = new Promise(function(resolve, reject) {
     4   console.log('Promise');
     5   resolve();
     6 });
     7 promise.then(function() { //成功时候的调用
     8   console.log('resolved.');
     9 }).catch(function (reason) { //异常时候的调用
    10     console.log('失败:' + reason);
    11 });
     
    以上代码理解:Promise 传入 成功以及失败的方法  .then()//这里调用的成功的方法  

    //串行调用:
    p.then(multiply)
    .then(add)
    .then(multiply)
    .then(add)
    .then(function (result) {
        log('Got value: ' + result);
    });

    并行调用与容错处理 (聊天室获取各个用户说的) 
    //并行调用: Promise.all
    var p1 = new Promise(function (resolve, reject) {
        setTimeout(resolve, 500, 'P1');
    });
    var p2 = new Promise(function (resolve, reject) {
        setTimeout(resolve, 600, 'P2');
    });
    // 同时执行p1和p2,并在它们都完成后执行then:
    Promise.all([p1, p2]).then(function (results) {
        console.log(results); // 获得一个Array: ['P1', 'P2']
    });
     
    //但是为了容错 就是用Promise.race 谁执行快就先用谁的
    var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
    });
    var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
    });
    Promise.race([p1, p2]).then(function (result) {
    console.log(result); // 'P1'
    });

     
     
     
  • 相关阅读:
    Linux_修改网卡名
    综合架构_ansible_剧本编写
    综合架构_ansible自动化管理服务
    Linux_综合架构_ssh基于密钥_远程连接
    NFS项目实践
    综合架构_实时同步服务 inotify
    综合架构_nfs常见错误
    linux_知识点集锦
    企业全网备份数据
    综合架构_存储服务nfs
  • 原文地址:https://www.cnblogs.com/lanSeGeDiao/p/8859131.html
Copyright © 2011-2022 走看看