我有这个vue2代码:
checkUser2() {
var returnValue;
axios.get(`api/users/CheckUsername/${this.username}`)
.then(response => {
returnValue = response.data.error === 0;
}, errorCallBack => {
returnValue = false;
});
return returnValue;
}
我称之为:
var a = this.checkUser2();
console.log(a);
并且它总是返回undefined。我做错了什么?
答案 0 :(得分:6)
如果要从此方法返回值,则必须从函数返回 promise 并使用回调来成功捕获结果。
@Component
@DisallowConcurrentExecution
public class Job1 implements Job {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Value("${schedule}")
private String frequency;
@Autowired
private Service service;
@Override
public void execute(JobExecutionContext jobExecutionContext) {
log.info("execute");
}
@Bean(name = "jobBean1")
public JobDetailFactoryBean job() {
return SchedulerConfig.createJobDetail(this.getClass());
}
@Bean(name = "jobBean1Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean1")JobDetail jobDetail) {
return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}
当你打电话时:
@Component
@DisallowConcurrentExecution
public class Job2 implements Job {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Value("${schedule}")
private String frequency;
@Autowired
private Service service;
@Override
public void execute(JobExecutionContext jobExecutionContext) {
log.info("execute");
}
@Bean(name = "jobBean2")
public JobDetailFactoryBean job() {
return SchedulerConfig.createJobDetail(this.getClass());
}
@Bean(name = "jobBean2Trigger")
public CronTriggerFactoryBean jobTrigger(@Qualifier("jobBean2")JobDetail jobDetail) {
return SchedulerConfig.createCronTrigger(jobDetail, frequency);
}
答案 1 :(得分:0)
我对vue2一无所知,但我知道axios
对promises有效,所以因为你在你的诺言之外返回returnValue
,你的函数返回{{1}的当前值},这是returnValue
。
答案 2 :(得分:0)
这是因为您在请求发出之前返回了值。你需要制作一个Promise,当它结算时,返回值。
checkUser2() {
return new Promise((resolve, reject) => {
var returnValue;
axios.get(`api/users/CheckUsername/${this.username}`)
.then(response => {
returnValue = response.data.error === 0;
resolve(returnValue);
}, errorCallBack => {
returnValue = false;
reject(returnValue);
});
});
}
然后你只需要像这样调用它来获取值:
this.checkUser2().then(val => {
a = val;
})
希望这会对你有所帮助。