问题是不是跟VueJS都没有Axios ...我想你误解了Promises
你的函数是异步的,并使用Promise来解决问题,以及axios。
要有allContactsSaved()与真/假回来供以后使用,你有3种选择:
1.承诺
返回一个承诺,和使用。那么当allContactsSaved是所谓的,就像这样:
// 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引擎的版本,你需要一个transpiler
// 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);
}
的可能的复制[如何如何从异步调用返回响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Svenskunganka
如何使用回调函数在我的例子? –