private isValidURL(url: string) {
var isValid = false;
this.$http.get(url).then(
(data) => {
console.log('success');
isValid = true;
}
).catch(
(reason) => {
console.log('failure ' + reason);
isValid = false;
}
).then(
() => {
return isValid;
}
)
}
private anotherFunc() {
if (!this.isValidURL(url)) {
alert('Wrong URL');
return false;
}
}
if语句中的警报正在isValidURL
函数调用之前执行。如何确保首先执行该功能?
答案 0 :(得分:0)
使用承诺。 console.log
调用的长版本就是这个
private isValidURL(url: string) {
return new Promise((resolve, reject) => {
this.$http.get(url).then(
(data) => {
console.log('success');
resolve();
}
).catch(
(reason) => {
console.log('failure ' + reason);
reject();
}
);
}
private anotherFunc() {
this.isValidURL(url).catch(){
alert('Wrong URL');
return false;
}
}
或简短版本,只需使用$http
返回的承诺
private isValidURL(url: string) {
return this.$http.get(url);
}
private anotherFunc() {
this.isValidURL(url).catch(){
alert('Wrong URL');
return false;
}
}
答案 1 :(得分:0)
不确定ts语法,但是像这样:
private isValidURL(url: string) {
return this.$http.get(url)
.then(() => true, () => false);
}
private anotherFunc() {
this.isValidURL(url)
.then(isValid => {
console.log(isValid ? 'Valid' : 'Invalid');
});
}