javascript - 如何返回一个已经在 Javascript/ReactNative 中'thenned'的承诺?
问题描述
使用以下代码:
makeRequest = async (path, body) => {
let client = await this.getClient()
return this.client.post(path, body).then((response) => {
console.log("Response on NetModule.makeRequest: ", response)
if (!responseIsSuccess(response)) { toast("The response shows some errors.") }
return response
}).catch((error) => {
toast("The request failed")
})
}
login = async (username, password) => {
let body = { username: username, password: password)
return this.makeRequest('/login', body).then((response) => {
console.log("Response on NetModule.login: ", response)
if (responseIsSuccess(response)) { saveResponseToDisk(response); }
return response
})
}
btnLoginClick = async () => {
const { username, password } = this.state
NetModule.login(username, password).then((response) => {
console.log("Response on LoginScreen.btnLoginClick: ", response)
if (responseIsSuccess(response)) { this.props.navigation.navigate(home) }
return response
})
}
回应是:
Response on NetModule.login: undefined
Response on LoginScreen.btnLoginClick: undefined
Response on NetModule.makeRequest: <has response>
为什么会这样?我怎样才能使响应是这样的(并按此顺序):
Response on NetModule.makeRequest: <has response>
Response on NetModule.login: <has same response>
Response on LoginScreen.btnLoginClick: <has same response>
解决方案
不要混搭,async/await
如果.then
你不需要的话。当前的问题是它btnLoginClick
不会“等待”NetModule.login
完成。它立即返回。return NetModule.login
可以解决这个问题,但我们可以做得更好:
makeRequest = async (path, body) => {
let client = await this.getClient()
try {
let response = await client.post(path, body)
console.log("Response on NetModule.makeRequest: ", response)
if (!responseIsSuccess(response)) { toast("The response shows some errors.") }
return response
} catch (error) {
toast("The request failed")
}
}
login = async (username, password) => {
let body = { username: username, password: password)
let response = await this.makeRequest('/login', body)
console.log("Response on NetModule.login: ", response)
if (responseIsSuccess(response)) { saveResponseToDisk(response); }
return response
}
btnLoginClick = async () => {
const { username, password } = this.state
let response = await NetModule.login(username, password);
console.log("Response on LoginScreen.btnLoginClick: ", response)
if (responseIsSuccess(response)) { this.props.navigation.navigate(home) }
return response
}
推荐阅读
- go - 如何处理 ssh.StdoutPipe() 的特定字符
- c# - 如何使用 C# 从具有 TextValue 格式元素的 xml 中的多个节点读取值
- python - 有没有办法在没有唯一 ID 的 Selenium 网页上选择一个项目?
- google-apps-script - 谷歌应用程序脚本异步等待表格 api
- r - 根据另一个向量中的值在 r 中创建逻辑向量
- hl7-fhir - 为 FHIR 设置 SMART 应用程序并利用现有资源
- reactjs - 如何根据单击的单选按钮显示和隐藏文本字段类型编号?
- python-3.x - valueError:在使用 google oauth 客户端和同时请求时对关闭的文件进行 I/O 操作
- sqlalchemy - 在 SQLAlchemy 中更新现有子对象并将新子对象附加到父对象的有效方法是什么?
- react-native - VictoryLabel 坐标与 VictoryChart 域不匹配