文章目录
环境搭建
npm init -y
npm install --save express
- 服务器端
//server.js
const express = require("express");
const server = express();
server.use(express.static(__dirname));
server.get("/data",function(req,res){
const user = {
name:"左一",
address:"上海 "
}
res.json(user);
});
server.get("/name",function(req,res){
const name = "左一";
res.send(name);
})
server.listen("3030",function(){
console.log("listening on *:3030");
})
- 浏览器端
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./index.js"></script>
</body>
</html>
//index.js
function getDataFromServer(){
return fetch("/data").then(function(response){
return response.json();
}).then(function(user){
console.log(user);
return user;
})
}
function getName(){
return fetch("/name").then(function(response){
return response.text();
}).then(function(name){
console.log(name);
return name;
})
}
回调函数作参数
//index.js
function getDataFromServer(callback){
fetch("/data").then(function(response){
return response.json();
}).then(function(user){
callback(user);
})
}
function preprocessBeforeRendering(user,callback){
const str = `${user.name}他现在在${user.address}`;
callback(str);
}
function render(htmlString){
document.body.innerHTML = htmlString;
}
getDataFromServer(function(user){
preprocessBeforeRendering(user,function(htmlString){
render(htmlString);
})
})
Promise
new Promise().then()
//index.js
// function getDataFromServer(){
// return new Promise((resolve,reject) => {
// const XHR = new XMLHttpRequest();
// XHR.open("get","/data/1");
// XHR.onreadystatechange = function(){
// if(XHR.status===200 && XHR.readyState===4){
// resolve(JSON.parse(XHR.response));
// }else{
// reject(XHR.statusText);
// }
// }
// XHR.send();
// })
// }
function getDataFromServer(){
return fetch("/data").then(function(response){
return response.json();
}).then(function(user){
return user;
})
}
function preprocessBeforeRendering(user){
return `${user.name}他现在在${user.address}`;
}
function render(htmlString){
document.body.innerHTML = htmlString;
}
getDataFromServer()
.then(function(user){
return preprocessBeforeRendering(user);
}).then(function(htmlString){
render(htmlString);
})
fetch
返回一个Promise对象then(onFulflled,onRejected)
接受两个参数,返回一个Promise对象onFulfilled
异步操作成功时调用的回调函数
回调函数的参数是异步操作的结果onRejected
异步操作失败时调用的回调函数
回调函数的参数是异步操作的结果
Promise.resolve().then()
//index.js
function getDataFromServer(){
return fetch("/data").then(function(response){
return response.json();
}).then(function(user){
return user;
})
}
function preprocessBeforeRendering(user){
return `${user.name}他现在在${user.address}`;
}
function render(htmlString){
document.body.innerHTML = htmlString;
}
Promise.resolve()
.then(getDataFromServer)
.then(preprocessBeforeRendering)
.then(render);
// [getDataFromServer,preprocessBeforeRendering,render].reduce((p,fn)=>p.then(fn),Promise.resolve());
// const applyAsync = (p,fn) => p.then(fn);
// const composeAsync = (...funcs) => funcs.reduce(applyAsync,Promise.resolve());
// composeAsync(getDataFromServer,preprocessBeforeRendering,render);
Promise.resolve()
,手动创建一个已经resolve的Promise对象。
异步之加载图像
function loadedImgAsync(url,elm){
return new Promise((resolve,reject) => {
var img = new Image();
img.onload = function(){
resolve(`loaded image at ${url}`)
}
img.onerror = function(){
reject(new Error(`could not loaded image at ${url}`));
}
img.src = url;
elm.appendChild(img);
})
}
// loadedImgAsync("./imgs/d.png",document.body)
// .then(
// tip => console.log(tip),
// err => console.log(err)
// );
loadedImgAsync("./imgs/d.png",document.body)
.then(tip => console.log(tip))
.catch(tip => console.log(tip));
async…await
//index.js
function getDataFromServer(){
return fetch("/data").then(function(response){
return response.json();
}).then(function(user){
return user;
})
}
function preprocessBeforeRendering(user){
return `${user.name}他现在在${user.address}`;
}
function render(htmlString){
document.body.innerHTML = htmlString;
}
async function init(){
const user = await getDataFromServer();
const htmlString = preprocessBeforeRendering(user);
render(htmlString);
}
init();
async function
返回一个Promise对象await
该关键词只在async function
内有效
async...await
允许我们以类似同步方式书写异步代码。
异步之定时器
const timeout = ms => new Promise(resolve => setTimeout(resolve,ms));
const asyncPrint = async (value,ms) => {
await timeout(ms);
console.log(value);
}
asyncPrint("hello world",1000*2);
刷新页面2秒后,控制台打印出"hello world"。
异步之读取文件
const fs = require("fs");
const readFile = (url) => {
return new Promise((resolve,reject) => {
fs.readFile(url,"utf8",(err,data) => {
if(err) reject(err);
resolve(data);
})
})
}
const asyncReadFile = async (url) => {
const fileContent = await readFile(url);
console.log(fileContent);
}
asyncReadFile("./index.html");