Javascript 如何打破axios承诺的条件?
在vue.js应用程序中,我有一部分处理获取数据以进行无限制分页:Javascript 如何打破axios承诺的条件?,javascript,promise,vue.js,axios,Javascript,Promise,Vue.js,Axios,在vue.js应用程序中,我有一部分处理获取数据以进行无限制分页: fetchData() { this.loading = true this.page++; axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then( response => this.jokes = response.data) .then( if (this.jo
fetchData() {
this.loading = true
this.page++;
axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then( response =>
this.jokes = response.data)
.then( if (this.jokes.length == null) {throw new Error("end of pagination")} )
.catch(function (error) {
});
document.body.scrollTop = document.documentElement.scrollTop = 0;
this.loading = false;
};
我想停止渲染空笑话
,如果响应为空,则中断函数。正如您在关于ve的代码中所看到的,我在另一个中添加了一个条件,但在if
中出现了错误:
Module build failed: SyntaxError: Unexpected token (169:20)
所以我想知道实现这一目标的正确方法是什么 您必须
向附加回调函数,然后
承诺
fetchData() {
this.loading = true
this.page++;
axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then(function( response){
this.jokes = response.data;
return this.jokes;
}).then(function(response){
if (!response || response.length == 0) {
throw new Error("end of pagination")
}
}).catch(function (error) {
});
document.body.scrollTop = document.documentElement.scrollTop = 0;
this.loading = false;
}
或者使用箭头
函数和包装
带有{}
的条件
.then(()=>{
if (this.jokes.length == null) {
throw new Error("end of pagination")
}
}
})
代码中的问题是then
回调定义不正确
.then(() => if (this.jokes.length == null) {throw new Error("end of pagination")})
您需要用括号括起来{}
:
.then(() => {
if (this.jokes.length == null) {
throw new Error("end of pagination")
}
})
另一个问题是,您定义了一个额外的回调,然后回调,并错误地验证笑话数组是否为空(而不是this.jokes.length==null
,验证它是否已定义且长度等于零):
在中添加括号{}
,然后在回调中添加括号。@alexmac您能详细说明一下如何操作吗?我是js新手。您周围没有函数表达式if
语句。这将删除错误。但我仍然得到了最后一页,其中没有任何内容,这正是我想要避免的。知道怎么做吗?@Karlom,是的,只需先返回然后返回
。这会导致未捕获(承诺中)错误:分页结束
,甚至在第一页。所以我想条件需要重写。你确定第一页的笑话不是空的吗?在callback的顶部添加console.log(笑话)
。是的,在第6页之前会有笑话。顺便说一句,在fetchData
的顶部,您会增加页面,因此它从1开始(如果是0),而不是从0开始。console.log(笑话)
是否打印一些内容?
.then(response => {
let jokes = response.data;
if (!jokes || jokes.length === 0) {
throw new Error("end of pagination");
}
this.jokes = jokes;
});