<template> <div> <span>{{ x }}</span> <br> <span>{{ y }}</span> <br> <h1>-----------</h1> <button @click="foo">click</button> </div> </template> <script> export default { name: 'Await', data() { return { x: '1', y: '2' } }, mounted() { this.change() }, methods: { async change() { await this.change2() await this.change1() }, async change1() { console.log('=====change1') const _this = this return new Promise((resolve) => { setTimeout(() => { _this.x = 'x' resolve() // 必须要有resolve, await才能生效 }, 500) }) }, async change2() { console.log('=====change2') const _this = this return new Promise((resolve) => { setTimeout(() => { _this.y = 'y' resolve() // 必须要有resolve, await才能生效 }, 500) }) }, async foo() { var a = await new Promise((resolve) => { setTimeout(() => { resolve(1) }, 2000) }) console.log(a) // 第2秒时输出: 1 try { var b = await new Promise((resolve, reject) => { setTimeout(() => { reject(2) }, 1000) }) } catch (e) { console.log(e) // 第3秒时输出: 2 } // 函数暂停2秒后再继续执行 var sleep = await new Promise((resolve) => { setTimeout(() => { resolve('sleep') }, 2000) }) var c = await 3 console.log(c) // 第5秒时输出: 3 } } } </script> <style scoped> </style>
await搭配promise使用
最新推荐文章于 2024-06-24 12:32:11 发布