Promise、async和await
async和await
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| function getName() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("John Doe"); }, 2000); }); }
async function getAge() { return 25; }
function getPwd() { return Promise.resolve(123456); }
async function test() { const name = getName(); const name1 = await getName(); console.log(name); console.log(name1);
const age = getAge(); const age1 = await getAge(); console.log(age); console.log(age1); const pwd = getPwd(); const pwd1 = await getPwd(); console.log(pwd); console.log(pwd1); }
test();
|
Promise
一个promise有三种状态, 且状态只能改变一次
同步状态下, 先改变状态, 再执行回调; 异步下, 先执行回调, 再改变状态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
function getName(callback) { setTimeout(() => { callback("John Doe"); }, 2000); } getName(name => { console.log(name); });
function getAge() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(18); }, 2000); }); }
getAge() .then(age => { console.log(age, 1); return age; }) .then(age => { console.log(age, 2); return age; });
const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve("John Doe"); reject("Error"); }, 2000); });
promise .then(name => { console.log(name); }) .catch(error => { console.log(error); }) .finally(() => { });
|
模拟axios
使用XMLHttpRequest和Promise封装一个简单的Axios
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const axios = ({ method = "get", url }) => { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.responseType = "json"; xhr.send(); xhr.onreadystatechange = () => { if (xhr.readyState == 4) { if (xhr.status / 100 == 2) resolve(xhr.response); else reject(xhr.status); } }; }); }; axios.get = url => axios({ url }); axios.post = url => axios({ method: "POST", url });
axios({ url: "https://api.uomg.com/api/rand.qinghua" }) .then(res => { console.log(res); }) .catch(err => { console.log(err); });
axios.get("https://api.uomg.com/api/rand.qinghua").then(res => { console.log(res); });
|
更多