javascript/vue.js async/await and .then (promise) 不等到登录函数中的提取完成
javascript/vue.js async/await and .then (promise) not waiting until completion of fetch in login function
我构建了一个登录功能并在我的后端服务器上检查凭据。我必须等待服务器的响应。我使用了 es7-async-await.js 的官方指南,但它不起作用。我已经尝试了 async/await 和 promises 提供的一切,但它根本不起作用。我阅读了有关此问题的所有帖子。我做错了什么?
我的函数:
async getCredentials(pUser, pCipher) {
var url = new URL(serviceURL);
var params = {
user: pUser,
p: pCipher
}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
// await response of fetch call
let response = await fetch(url, {
method: 'get',
headers: { }
});
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
return data;
},
我的函数调用:
this.getCredentials(this.input.username, cipher)
.then(data => this.checkResponse = data.items)
.catch(reason => console.log(reason.message))
console.log("data: ->>>> " ,this.checkResponse);
结果:
数据总是空的,因为函数没有等待
你能把 console.log 放在 .then 中吗?打印东西吗?如果在未收到数据时执行 console.log 将不会打印任何内容。
this.getCredentials(this.input.username, cipher)
.then(data =>
{
this.checkResponse = data.items
console.log("data: ->>>> " ,this.checkResponse);
})
.catch(reason => console.log(reason.message))
我构建了一个登录功能并在我的后端服务器上检查凭据。我必须等待服务器的响应。我使用了 es7-async-await.js 的官方指南,但它不起作用。我已经尝试了 async/await 和 promises 提供的一切,但它根本不起作用。我阅读了有关此问题的所有帖子。我做错了什么?
我的函数:
async getCredentials(pUser, pCipher) {
var url = new URL(serviceURL);
var params = {
user: pUser,
p: pCipher
}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
// await response of fetch call
let response = await fetch(url, {
method: 'get',
headers: { }
});
// only proceed once promise is resolved
let data = await response.json();
// only proceed once second promise is resolved
return data;
},
我的函数调用:
this.getCredentials(this.input.username, cipher)
.then(data => this.checkResponse = data.items)
.catch(reason => console.log(reason.message))
console.log("data: ->>>> " ,this.checkResponse);
结果:
数据总是空的,因为函数没有等待
你能把 console.log 放在 .then 中吗?打印东西吗?如果在未收到数据时执行 console.log 将不会打印任何内容。
this.getCredentials(this.input.username, cipher)
.then(data =>
{
this.checkResponse = data.items
console.log("data: ->>>> " ,this.checkResponse);
})
.catch(reason => console.log(reason.message))