2017-08-04 43 views
0

返回布尔在VueJS我试图与爱可信如何与爱可信

allContactsSaved() { 
    let promise = axios.get('/contacts'); 
    console.log(promise.then(function (response) { 
     response.data.data.forEach(function(contact) { 
      if (!contact.saved) { 
      return false; 
      } 
     }); 
     return true; 
    })); 
    } 

的执行console.log只是返回

承诺返回一个布尔{[PromiseStatus]:“待定“,[[PromiseValue]]:undefined}

但我希望返回true或false。

+2

的可能的复制[如何如何从异步调用返回响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Svenskunganka

+0

如何使用回调函数在我的例子? –

回答

0

问题是不是跟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); 
} 
0

您可以使用every,以确保每个联系人保存

return response.data.ever(contact => contact.saved) 

但是,这仍然会返回一个承诺 你可以链中的另一个承诺:

allContactsSaved() { 
let promise = axios.get('/contacts'); 
promise.then(function (response) { 
    return response.data.ever(contact => contact.saved) 
}).then((areTheySaved) => { 
    console.log(areTheySaved); 
}); 

}

+0

我得到正确的输出,然后在console.log中。但是,如果我在其他地方调用函数来检查它是否返回true或false,我不及时得到返回结果,因为它是异步的。如何等待响应? –

+0

在使用承诺时返回'allContactsSaved'中的承诺并调用'.then' – Posva