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'
    });

     
     
     
  • 相关阅读:
    宠物店4.0的安装
    《professional asp.net 2.0》读书笔记连载2
    《xhtml 入门系列》之一
    ALinq 让Mysql变得如此简单
    ALinq 入门学习(八)ALinq 对Vs2010 的支持
    教你一款极为简单实用的图表插件
    虚拟机下无法启动 Linux 系统
    怎样去突破文件依赖缓存
    jQuery 表单验证扩展(五)
    Log4Net 全方位跟踪程序运行
  • 原文地址:https://www.cnblogs.com/lanSeGeDiao/p/8859131.html
Copyright © 2011-2022 走看看