我对Vue有点陌生,所以请客气。我有一个简单的推送电话,我想在用户将照片上传到我的应用后运行2秒。我正在尝试在axios内执行“然后”操作,但操作会立即发生。我想让它在2秒后发生。如何使用setTimeout完成此操作?
我在这里看到了答案... How to add delay to promise inside then
但是我的内心在试图理解它。
```
axios.put(`${process.env.KITTY_URL}/api/v1/cats/${this.singleCat.id}/`,formData,{
onUploadProgress: progressEvent => {
console.log('Upload progress: ' + Math.round(progressEvent.loaded / progressEvent.total * 100) + '%')
}
})
.then(response => {
response.status === 200 ? this.showSuccess = true : this.showDanger = true;
this.singleCat = response.data;
// NOTE: set a timer to run this line 2 seconds after success response
setTimeout(function() { this.$router.push('/login'); }, 2000)<---WHAT SHOULD THIS LOOK LIKE?
})
.catch(error => {
console.log(error);
this.showDanger = true;
})
```
答案 0 :(得分:0)
首先,您需要绑定上下文。最简单的方法就是使用箭头功能。因此,您只需要将该行更改为此:
setTimeout( () => this.$router.push('/login'), 2000);
另一种方法是使用异步/等待:
let response = await axios.put(...);
setTimeout( () => this.$router.push('/login'), 2000);
尽管您不会以这种方式处理错误:https://github.com/axios/axios/issues/1086