在学习wepy做小程序开发时,经常看到.wpy文件中会声明异步函数,于是专门去找了这块儿的东西看了看。结合之前使用的promise,写一下自己的理解:
之前做异步操作时,比较常用promise和then(),由于then()返回的仍然是priomise对象,所以这是一种链式的书写方式。
例如当我写一个请求时:
import axios from 'axios'
function sendRequest(){
let str = null;
axios.get('/api/investor' + '?page=1').then(res => {
str = res.data;
console.log(str); // {...some data...}
});
console.log(str); // null
}
异步的操作是写在then()里面的
使用async和await的方式:
import axios from 'axios'
async sendRequest(){
let str = null;
let res = await axios.get('/api/investors' + '?page=1');
console.log(res) // {...some data...}
str = res;
}
使用async声明这是异步函数,程序执行到await这行时,await后面一般是Promise对象,并且返回resolve后的结果。然后程序继续执行,打印出res的值。async中return会返回一个Promise。(函数永远不可能return 异步操作返回的结果,所以async只是promise写法的语法糖)