Promise

参考资料:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

一、概述

ECMAscript 6 原生提供了 Promise 对象。

Promise 对象用于表示一个异步操作的最终完成 (或失败)及其结果值。

一个 Promise 必然处于以下几种状态之一:

  • 待定(pending): 初始状态,既没有被兑现,也没有被拒绝。
  • 已兑现(fulfilled): 意味着操作成功完成。
  • 已拒绝(rejected): 意味着操作失败。

待定状态的 Promise 对象要么会通过一个值被兑现(fulfilled),要么会通过一个原因(错误)被拒绝(rejected)

当这些情况之一发生时,我们用 promise 的 then 方法排列起来的相关处理程序就会被调用。

如果 promise 在一个相应的处理程序被绑定时就已经被兑现或被拒绝了,那么这个处理程序就会被调用,

因此在完成异步操作和绑定处理方法之间不会存在竞争状态。

二、构造函数

Promise 构造器主要用于包装不支持promise(返回值不是Promise)的函数。

我们通过new关键字和Promise构造器创建它的对象。这个构造器接受一个名为"executor function"的函数。

这个函数应当接受两个函数参数。

当异步任务成功时,第一个函数(resolve)将被调用,并返回一个值代表成功。

当其失败时,第二个函数(reject)将被调用,并返回失败原因(失败原因通常是一个error对象)。

const myFirstPromise = new Promise((resolve, reject) => {
  // do something asynchronous which eventually calls either:
  //
  //   resolve(someValue)        // fulfilled
  // or
  //   reject("failure reason")  // rejected
});

三、接口请求测试

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        requestUrl("http://123.56.67.147:3312/cesiumdemo/projConvert/getSpatialBySRID/4326").then(res => {
            alert(res);
        }).catch(err => {
            alert(err);
        })
        function requestUrl(url) {
            let promise = new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest();
                var method = "GET";
                xhr.open(method, url, true);
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        resolve(xhr.response);
                        console.log(xhr.responseText)
                    } else {
                        reject(xhr.responseType);
                    }
                }
                xhr.onerror = function () {
                    reject(Error('There was a network error.'));
                }
                xhr.send();
            })
            return promise;

        }

    </script>
</body>

</html>

四、静态方法

 

 

五、并发请求测试

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
     let urls=["http://123.56.67.147:3312/cesiumdemo/projConvert/getSpatialBySRID/4326",
        "http://123.56.67.147:3312/cesiumdemo/projConvert/getSpatialBySRID/32650",
        "http1://123.56.67.147:3312/cesiumdemo/projConvert/getSpatialBySRID/32649错误的url",
        "http://123.56.67.147:3312/cesiumdemo/projConvert/getSpatialBySRID/32649查询出错",
        "http://123.56.67.147:3312/cesiumdemo/projConvert/getSpatialBySRID/4490",
        "http://123.56.67.147:3312/cesiumdemo/projConvert/getSpatialBySRID/3857"];
        let promises=[];
        urls.forEach(v=>promises.push(requestUrl(v)));
        Promise.allSettled(promises).then(results=>{
            console.log(results);
        }).catch(err=>{
            alert(err);
        })
        function requestUrl(url) {
            let promise = new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest();
                var method = "GET";
                xhr.open(method, url, true);
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        resolve(xhr.response);
                        console.log(xhr.responseText)
                    } else {
                        reject(xhr.responseType);
                    }
                }
                xhr.onerror = function () {
                    reject(Error('There was a network error.'));
                }
                xhr.send();
            })
            return promise;

        }
    </script>
</body>
</html>

 

返回结果:

 

posted on 2022-01-18 00:45  苹果园dog  阅读(47)  评论(0编辑  收藏  举报

导航