首页 > 解决方案 > 如何返回一个已经在 J​​avascript/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>

标签: javascriptreact-nativeasynchronous

解决方案


不要混搭,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
}

推荐阅读