VueJs中的Javascript:如何从异步获取而不是承诺返回数据对象
我准备采取这一行动VueJs中的Javascript:如何从异步获取而不是承诺返回数据对象,javascript,vuejs2,promise,fetch,Javascript,Vuejs2,Promise,Fetch,我准备采取这一行动 actions: { testLogin(context, credentials) { const loginService = new FetchClient(); let d = loginService.post('login', credentials); console.log(d); }, 并且该函数在另一个类中导入存储 async post(endpoint, params) { awa
actions: {
testLogin(context, credentials) {
const loginService = new FetchClient();
let d = loginService.post('login', credentials);
console.log(d);
},
并且该函数在另一个类中导入存储
async post(endpoint, params) {
await fetch(this.url + endpoint, {
'method': 'POST',
headers: this.headers,
body: JSON.stringify(params),
})
.then(response => {
return response.json();
})
.then( (data) => {
this.returnData = data.data;
})
.catch(error => {
console.log(error);
});
return this.returnData;
}
我得到了
Promise{}
,我可以从fetch类中提取数据,但是如果我在存储中,就不能访问数据,因为它是Promise而不是对象。如何解决此问题?将return语句放入第二个块中,然后块:
async post(endpoint, params) {
await fetch(this.url + endpoint, {
'method': 'POST',
headers: this.headers,
body: JSON.stringify(params),
})
.then(response => {
return response.json();
})
.then( (data) => {
this.returnData = data.data;
return this.returnData;
})
.catch(error => {
console.log(error);
});
}
我甚至建议您使用以下代码以提高可读性:
async post(endpoint, params) {
const response = await fetch(this.url + endpoint, {
'method': 'POST',
headers: this.headers,
body: JSON.stringify(params),
})
if (!response.ok) {
const message = `An error has occured: ${response.status}`;
throw new Error(message);
}
const resp_data = await response.json()
return resp_data.data
}
然后像这样调用您的方法:
post(endpoint, params)
.then(data => {// do something with data})
.catch(error => {
error.message; // 'An error has occurred: 404'
});
请参阅《异步/等待指南》是否可以尝试:
async testLogin(context, credentials) {
const loginService = new FetchClient();
let d = await loginService.post('login', credentials);
console.log(d);
}
作为async
方法返回您需要使用的承诺。简单地说,如果没有心理或时间旅行,异步结果就无法同步-javascript不包含任何内容。我们建议始终添加try/catch块,以便更好地处理错误。它确实记录了数据,但在我使用的js文件中,我发现它作为承诺而不是数据返回
As @Ayudh mentioned, try the following code:
async post(endpoint, params) {
try{
let response = await fetch(this.url + endpoint, {
'method': 'POST',
headers: this.headers,
body: JSON.stringify(params),
});
let data = await response.json();
this.returnData = data.data;
}catch(e){
console.log(e);
}
return this.returnData;
}