ES6---axios執行原理
Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中
http://www.axios-js.com/zh-cn/docs/

1.
axios.get('1111.json')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
console:

2.
axios.get('1111.json')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
console.log(123);
console:

3. axios.get相當于new了一個promise,具體如下圖:

4.
async function tt() { await axios.get('1111.json') .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); console.log(123); }; tt();
console:

5. 用await 先取出了資料
async function tt() { await axios.get('1111.json')//先取出了資料 .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); document.getElementById("aa").innerHTML = '<div>123</div>'; }; tt();
console:

6. 用await先獲取資料,不然就先執行后面的:document.getElementById("aa").innerHTML = '<div>' + yy + '</div>';
var yy = ''; async function tt() { await axios.get('1111.json')//先通過URL從服務器獲取資料,再顯示到頁面 .then(response => { yy = response.data.username; console.log(response.data); }) .catch(error => { console.log(error); }); document.getElementById("aa").innerHTML = '<div>' + yy + '</div>'; //用了await就先獲取資料了 }; tt();
7. 或者把DOM操作的放在axios里面也可以 (前提內嵌的不是很復雜,很復雜的放在外面用await比較好)
var yy = ''; async function tt() { await axios.get('1111.json')//先通過URL從服務器獲取資料,再顯示到頁面 .then(response => { yy = response.data.username; console.log(response.data); document.getElementById("aa").innerHTML = '<div>' + yy + '</div>'; }) .catch(error => { console.log(error); }); }; tt();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/117327.html
標籤:JavaScript
上一篇:nodeErr - TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
