JavaScript Promise 使用

前几天看了一篇文章介绍 Javascript Promise 的用法,觉得Promise 很好,我又研究了 MDN 文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise,知道大概如何应用此函数。
先看几个英文词汇,promise 是承偌的意思, resolve坚定执行的意思,reject拒绝的意思, 放到一起组成 promise 函数体, 就是说先有承诺,如果承诺看起来很靠谱,则坚定执行 resolve()函数, 如果承诺很糟糕,则拒绝执行承偌,执行reject()函数。
promise  用来完成异步操作,如果异步操作完成了则执行resove(), 如果异步操作产生错误,则执行 reject().
new Promise(
function(resolve, reject) {
/*运行 异步操作*/
}
)  
注意这里的参数 resolve 是函数,异步完成时需要执行的函数。reject 也是函数,异步操作有故障时执行的函数。
Promise 是异步操作,什么时候执行完成不知道,等待执行结果...,执行成功了,执行resolve(), 不成功执行 reject().



promise 包括其他的几个函数
promise.all(), 必须是几个承偌都执行成功了,可以是几个函数窜在一起都成功, 才执行resolve()
promise.race(), 就算几个串在一起的承偌有一个承诺执行成功,就执行resolve().
 
几个例子
example 1
let myFirstPromise = new Promise((resolve, reject) => {
  //我们使用setTimeout()来模拟异步操作,在现实中我们使用Ajax XHR 或者是 HTML5 API 调用
  // In this example, we use setTimeout(...) to simulate async code. 
  // In reality, you will probably be using something like XHR or an HTML5 API.
  setTimeout(function(){
    resolve("Success!"); // Yay! Everything went well!
  }, 250);
});
//then() 函数就是当异步操作成功,执行resolve(), 就是执行then() 函数
myFirstPromise.then((successMessage) => {
//successMessage 就是 resolve() 函数的参数,一般来说是 字符串,但是也可以是其它类型参数。
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  console.log("Hello World! " + successMessage);
});

example 2
//javascript code
<script type='text/javascript'>
'use strict';
var promiseCount = 0;
function testPromise() {
    //计数器, 因为运行函数是因为按了 button, 按了几次按钮就会产生几个承诺
    let thisPromiseCount = ++promiseCount;
    let log = document.getElementById('log');
    log.insertAdjacentHTML('beforeend', thisPromiseCount +
        ') Started (<small>同步代码开始</small>)<br/>');
    //从1 开始的 promise
    // We make a new promise: we promise a numeric count of this promise, starting from 1
    let p1 = new Promise(
       (resolve, reject) => {
            log.insertAdjacentHTML('beforeend', thisPromiseCount +
                ') Promise started (<small>异步代码开始执行,什么时候结束不知道</small>)<br/>');
            // This is only an example to create asynchronism, 用setTimeout 来模拟正式的 异步操作
            window.setTimeout(
                function() {
                    // We fulfill the promise !
                    resolve(thisPromiseCount);
                }, Math.random() * 2000 + 1000);
        }
    );
    // We define what to do when the promise is resolved/rejected with the then() call, then() 函数就是 resolve() 函数。
    // and the catch() method defines what to do if the promise is rejected. catch() 函数就是 reject() 函数
    p1.then(
        // Log the fulfillment value
        function(val) {
            log.insertAdjacentHTML('beforeend', val +
                ') Promise fulfilled (<small>异步操作执行成功,返回</small>)<br/>');
        })
    .catch(
        // Log the rejection reason,失败原因
       (reason) => {
            console.log('记录失败原因 ('+reason+') 在这里.');
        });
    log.insertAdjacentHTML('beforeend', thisPromiseCount +
        ') Promise made (<small>同步操作结束</small>)<br/>');
}
<script>
//HTML code
<body>
<div id='log'></div>
<button οnclick='testPromise()'>TEST Promise</button>
</body>
运行的结果是 同步代码开始-->异步代码开始执行,什么时候结束不知道--> 同步操作结束--> 异步操作执行成功,返回, 因为异步操作结束时间不确定,所以先执行了第二个 同步操作代码


example 3 use ajax call PHP code. 需要jquery library.

  <script type='text/javascript'>
    'use strict';
    $(function(){
        var promiseCount = 0;
        $('#promise').click(function(){
        //计数器, 因为运行函数是因为按了 button, 按了几次按钮就会产生几个承诺   
        let thisPromiseCount = ++promiseCount;
        let log = document.getElementById('log');
        log.insertAdjacentHTML('beforeend', thisPromiseCount +
            ') Started (<small>同步代码开始</small>)<br/>');
        //从1 开始的 promise    
        // We make a new promise: we promise a numeric count of this promise, starting from 1
        let p1 = new Promise(
           (resolve, reject) => {
                log.insertAdjacentHTML('beforeend', thisPromiseCount +
                    ') Promise started (<small>异步代码开始执行,什么时候结束不知道</small>)<br/>');
                //ajax call PHP code, have 3 seconds sleep.
                var message ='';
                $.post('promise.php',
                    {},
                    function (data){
                        if (data.returnvalue == 'success') {
                           message = 'I have good sleep for three seconds';
                        } else {
                           message = 'I do not have a sleep';
                        }
                        // $('#log').text(message);
                        resolve(message);
                    },
                    'json'
                    );
            }
        );
        // We define what to do when the promise is resolved/rejected with the then() call, then() 函数就是 resolve() 函数。
        // and the catch() method defines what to do if the promise is rejected. catch() 函数就是 reject() 函数
        p1.then(
            // Log the fulfillment value
            function(message) {
                log.insertAdjacentHTML('beforeend', promiseCount +
                    ') Promise fulfilled, ' + message  + '(<small>异步操作执行成功,返回</small>)<br/>');
            })
        .catch(
            // Log the rejection reason,失败原因
           (reason) => {
                console.log('记录失败原因 ('+reason+') 在这里.');
            });
        log.insertAdjacentHTML('beforeend', thisPromiseCount +
            ') Promise made (<small>同步操作结束</small>)<br/>');
        })
    })
  </script>
//html code 
<body>
  <div id='log'></div>
  <button id= 'promise'>TEST Promise</button><br> 
 </body>


//php code, promise.php

<?php
sleep(3);
$return = 'success';
echo json_encode(array('returnvalue' => $return));
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值