异步编程之 Async与Await
2020-12-17 本文已影响0人
张德瘦嬢嬢
image
Async关键字
async异步,是一个关键字。用同步函数的写法声明异步函数。且异步返回的结果是一个Promise对象,通过 then(res) 方法捕捉成功返回的结果,通过 catch(error) 方法捕获错误的信息。
留下疑问:那么,函数本身的返回值呢?
async关键字
async function hello() { return "Hello" };
console.log(hello().constructor) //ƒ Promise() { [native code]
hello(); //hello调用返回的是promise对象
hello().then(console.log) //promise对象就有then方法 x=>console.log(x)简写等于 console.log
Await关键字
等待,是一个操作符。只能用在async函数中,await要等后面的Promise对象拿到结果,才继续执行函数里其他的代码。
async function fn(){
console.log('welcome')
var result=await new Promise((resolve,reject)=>{
setTimeout(function(){
resolve('zhang')
},2000);
});
console.log(result); //如果不用获取返回值,也可以直接执行语句:
console.log('de');
console.log('shou');
}
fn();
// welcome
// zhang //2秒后打出
// de
// shou
配合axios使用
—— Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
//getData.js
import axios from '../axios';
import qs from 'qs'
export const accountLogin = (phone, password) => axios.post("./app/ajaxLogin", qs.stringify({
mobile: phone,
password: password
})).then(response => {
return response;
}).catch(function (error) {
return error;
});
//login.vue
import {accountLogin,} from '@/service/getData'
methods:{
async login() {
if (this.phone == null || this.phone == "") {
this.$root.$emit("tips", {
text: "请输入手机号"
});
return false
}
if (isPhone(this.phone)) {
this.$root.$emit("tips", {
text: "请输入正确的手机号码"
});
return false;
}
if (this.password == null || this.password == "") {
this.$root.$emit("tips", {
text: "请输入密码"
});
return false;
}
if (isPassword(this.password)) {
this.$root.$emit("tips", {
text: "请输入正确的密码"
});
return false;
}
this.userInfo = await accountLogin(this.phone, this.password); //等待请求完成
this.$root.$emit("tips", {
text: this.userInfo.message
});
//记录用户信息
if (this.userInfo.success) {
this.GET_USERINFO(this.userInfo.data);
this.$router.push('./');
}
}
}