- await 必须要用在async里面,表示需要等待用了await这个词修饰的promise对象执行完才可以继续执行。
- 下面是我写的demo:
<script type="text/javascript"> function getPromise(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{console.log("successful");resolve(); },1000); }, ) } async function testAsync(){ await getPromise(); console.log("later"); } testAsync();//输出 successful,later 。去掉await输出later,successful </script>
- 用过vue axios请求插件的可以看下面这个应用实例:
test(){
let _this=this;
return _this.$axios({url:'test'});
},
async testAwait(){
let {data}= await this.test();
this.getProductList(data);//等待上面一行代码执行完才会执行这行代码
},
this.testAwait();
//当不需要方法的返回值时也可以这样写 axios和then返回的都是promise对象,.then返回链式函数
test(phone) {
let _this=this;
return _this.$axios({url:'test'
}).then(({data}) => {
console.log(1);
})
},
async testAwait(){
await this.test();
this.getProductList();
}
4 .关于Promise
a、js原本是同步执行的(从上往下执行)
b、Promise 是同步执行的,但他的回调函数(then/catch)是异步执行
下面是个例子
<script type="text/javascript">
//延迟函数
function waitTime(type, time) {
let startT = (new Date()).getTime()
while ((new Date()).getTime() - startT < time) {}
console.log(type);
}
function getPromise() {
return new Promise((resolve, reject) => {
//下面是同步执行
waitTime('promise', 1000) //1s后打印promise
reject() //执行catch or resolve() 执行then()
}, )
}
function testExecOrder() {
getPromise().then(() => {
//异步执行
waitTime('then', 1000)
}).catch(() => {
//异步执行
waitTime('catch', 1000)
})
console.log("later");
}
testExecOrder(); // promise later catch
</script>