• JavaScript中的Promise


    1.什么是Promise

    Promise是抽象异步处理对象以及对其进行操作的组件。Promise并不是从JavaScript中发祥的概念。Promise最初被提出是在 E语言中, 它是基于并列/并行处理设计的一种编程语言。另外,如果说到基于JavaScript的异步处理,我想大多数都会想到利用回调函数。可以说promise的功能是可以将复杂的异步处理轻松地进行模式化, 这也可以说得上是使用promise的理由之一。

    Promise的状态

    Promis有三种状态:

    1. Pending:进行中
    2. Resolved(Fulfilled):已完成
    3. Rejected:已失败;

    而promise状态变化只有两种:

    1. Pending --> Resolved
    2. Pending --> Rejected
    这意味着,一个Promise对象resolve之后,状态就一直停留在Resolved那里了,反过来reject也一样。
    这种特点的结果是,Promise对象的状态改变之后,你再给它添加回调函数,这个函数也会执行。
    这跟事件监听器很不一样 —— 你一旦错过某个事件,就没办法再捕获他了,除非这个事件再次发生。

    .then()和catch()

    Promise构造器接受一个函数作为参数,这个函数有两个参数:resolve,reject,分别代表这个Promise实例成功之后的回调函数和失败之后的回调函数。废话不多说直接上代码:

    var promise = new Promise(function (resolve, reject) {
        var a = 1
        if (a == 1) {
            resolve(a)
        } else {
            reject(error)
        }
    })
    promise.then(function (value) {
        console.log(value);
    }).catch(function (error) {
        console.log(error);
    })
    上述代码可输出: 1


    不管是then方法还是catch方法返回的都是一个新的Promise实例,这意味着Promise可以链式调用then和catch,每一个方法的返回值作为下一个方法的参数:
    var promise = new Promise(function (resolve, reject) {
        var a = 1
        if (a === 1) {
            resolve(a)
        } else {
            reject(error)
        }
    })
    promise.then(function (value) {
        console.log(value++)
        return value
    }).catch(function (error) {
        console.log(error)
    }).then(function (value) {
        console.log(value++)
    })
    
    // 输出:
    // 1
    // 2

    如果其中一个then失败了,它后面第一个catch方法就会接受这个错误并执行,然后继续执行后面的方法,比如:

    var promise = new Promise(function (resolve, reject) {
        resolve()
    })
    promise.then(function (value) { // 抛出错误
        console.log(1 / x)
    }).then(function () { // 此方法不会执行
        console.log('This "then" method will not happend!')
    }).catch(function (error) { // 接受错误,并打印出错误
        console.log('Have an error: ',error)
    }).then(function () { // 此方法会执行
        console.log('This "then" method  will happend!')
    })
    
    // 输出:
    /*
    Have an error:  ReferenceError: x is not defined
        at /Users/linxueying/Library/Mobile 
        ......
    This "then" method  will happend!
    */

    在前端项目当中,promise是非常重要的知识,按自己学习的知识总结了一下 希望对您的学习有帮助,加油!
     
  • 相关阅读:
    读后感悟
    使用java的循环单向链表解决约瑟夫问题
    稀疏数组
    java实现队列
    ASP.NET学习4. ASP.NET Ajax下POST完成后调用javascript函数
    ASP.NET学习3.前端和后台的相互调用
    ASP.NET学习1.使用“<% %>”嵌入代码
    ASP.NET学习2.弹出对话框的方法
    HTML5程序怎么打包成windows phne, ios和android的应用[转]
    PHP多文件上传个人理解总结 [转]
  • 原文地址:https://www.cnblogs.com/taxpolat/p/11418306.html
Copyright © 2020-2023  润新知