Promise的静态方法.all与.race的用法,搭配Ajax的XMLHttpRequest教学

首先是server.js文件内容,这里面的内容是用来开启一个node服务器,待会儿请求数据的时候需要用到:

const express = require('express')

var app = express()

app.get('/first',function(req,res){
    res.setHeader('Access-Control-Allow-Origin','*')
    res.send("hello Ajax1")
})

app.get('/second',function(req,res){
    res.setHeader('Access-Control-Allow-Origin','*')
    res.send("hello Ajax2")
})

app.get('/third',function(req,res){
    res.setHeader('Access-Control-Allow-Origin','*')
    res.send("hello Ajax3")
})

app.listen(8080,function(){
    console.log("8080端口已开启")
})

nodemon server.js运行

接下来是index.html内容:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
    </body>
    <script>

        function qurryData(url) {  
            return new Promise(function(resolve,reject){
                let xhr = new XMLHttpRequest()
                xhr.open('get',url)
                xhr.send(null)

                xhr.onreadystatechange = function(){
                    if(xhr.readyState !== 4)return;
                    if(xhr.readyState == 4 && xhr.status === 200){
                        resolve(xhr.responseText)
                    }else{
                        reject('error')
                    }
                }
            })
       }
       let p1 = qurryData('http://localhost:8080/first')
       let p2 = qurryData('http://localhost:8080/second')
       let p3 = qurryData('http://localhost:8080/third')
       //all要等所有的都执行完才打印
       Promise.all([p1,p2,p3]).then(function(result){
          console.log('all 里面的结果:' + result)
       })
       //race是谁第一个执行完就打印谁
       Promise.race([p1,p2,p3]).then(function(result){
          console.log('race 里面的结果:' + result)
       })
        // race比all先打印
        //所以最后结果是:
        // race 里面的结果:hello Ajax1 
        // all 里面的结果:hello Ajax1,hello Ajax2,hello Ajax3
    </script>
</html>

按F12打开控制台

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值