Javascript 函数在解析承诺之前未定义重新调整
我有一个vue程序,它使用服务从API调用获取产品Javascript 函数在解析承诺之前未定义重新调整,javascript,node.js,angular,vue.js,Javascript,Node.js,Angular,Vue.js,我有一个vue程序,它使用服务从API调用获取产品 getProducts() { axios.get("https://jsonplaceholder.typicode.com/posts").then(function (response) { return response; }).catch(function(error){ console.log(error); }) } 在需要调用此函数的vue页面中,我在created()钩
getProducts() {
axios.get("https://jsonplaceholder.typicode.com/posts").then(function (response) {
return response;
}).catch(function(error){
console.log(error);
})
}
在需要调用此函数的vue页面中,我在created()钩子中进行调用,如下所示:
created() {
//this returns a promise
productservices.getProducts().then(response =>{
this.products = response.data;
}).catch(error => console.log(error))
.finally(() =>{
consol.log("All done!");
})
},
我可以毫无问题地调用该函数,但是它正在运行.then()并返回未定义。为什么会这样?我怎么修理
getProducts() {
return axios.get("https://jsonplaceholder.typicode.com/posts")
}
试试这个
试试这个 您还可以使用async/await
async getProducts() {
try {
const response = await axios.get("https://jsonplaceholder.typicode.com/posts")
return response
} catch(e) {
// Do something with the error
console.log(e)
}
}
您还可以使用async/await
async getProducts() {
try {
const response = await axios.get("https://jsonplaceholder.typicode.com/posts")
return response
} catch(e) {
// Do something with the error
console.log(e)
}
}
在Axiost之前返回getProducts没有返回任何内容。。。。控制台中应该有错误。在Axiost之前返回getProducts中没有返回任何内容。。。。您的控制台中应该有错误。谢谢!这怎么行得通,但我做的不是?这是一个承诺。返回响应//这并没有回报一个承诺。可能是json。谢谢!这怎么行得通,但我做的不是?这是一个承诺。返回响应//这并没有回报一个承诺。可能是json。