微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

 

返回结果:

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐