首先是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打开控制台