Das Problem ist nicht mit VueJS weder Axios ... Ich glaube, Sie missverstehen Promises
Ihre Funktion ist asynchron und verwenden Sie Promises, um das Problem sowie Axios zu lösen.
Um allContactsSaved() Rückkehr mit true/false müssen später verwendet werden, haben Sie 3 Möglichkeiten:
1. Promises
Return ein Versprechen, und verwenden Sie .then wenn allContactsSaved ist genannt, wie folgt aus:
// 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. Rückrufe
Ich denke, die erste Option ist besser als diese. Das ist ein alter Schulweg.
// 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. Async/erwarten
Das ist neu für ES6/7 und ist abhängig von der Version von JS Motor, müssen Sie eine 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);
}
Mögliche Duplikat [How gebe ich die Antwort von einem asynchronen Anruf zurück?] (https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Svenskunganka
Wie kann ich die Rückruffunktion in meinem Beispiel? –