问题不在于 VueJS 也不在于 Axios……我认为你误解了 Promises
你的函数是异步的,使用 Promises 解决问题,还有 axios。
要让 allContactsSaved() 返回 true/false 以供以后使用,您有 3 个选项:
1.承诺
返回一个承诺,并在调用 allContactsSaved 时使用 .then,如下所示:
// Function
// Returns promise
allContactsSaved() {
let promise = axios.get('/contacts').then(function (response) {
// check if every one is saved
const check = response.data.data.every(function(contact) {
return contact.saved;
});
return check;
}));
return promise;
}
// Using it:
allContactsSaved().then(function(isSaved) {
console.log(isSaved);
});
2。回调
我认为第一个选项比这个更好。这有点老派的方式。
// Function
// Returns promise
allContactsSaved(callback) {
axios.get('/contacts').then(function (response) {
// check if every one is saved
const check = response.data.data.every(function(contact) {
return contact.saved;
});
if(callback) {
callback(check);
}
}));
}
// Using it with function callback:
allContactsSaved(function(isSaved) {
console.log(isSaved);
});
3.异步/等待
这是 ES6/7 的新功能,取决于 JS 引擎的版本,你需要一个转译器
// Function
// Returns promise
async allContactsSaved() {
const resp = await axios.get('/contacts');
const check = response.data.data.every(function(contact) {
return contact.saved;
});
return check;
}
// Using it, the caller function needs to be async:
async function() {
const result = await allContactsSaved();
console.log(result);
}