【问题标题】:React Native wait for one API call to finish before executing any othersReact Native 在执行任何其他 API 调用之前等待一个 API 调用完成
【发布时间】:2021-02-19 03:13:13
【问题描述】:

我正在用 react native 编写一个应用程序,它需要调用 API 以接收将用于所有其他 API 调用的不记名令牌,但我很难确保获取令牌的调用在进行任何其他调用之前完成。

我有一个基本的 APIHelper 类,它将包含应用程序需要进行的所有 API 调用的包装函数,这是它的简化版本:

export class APIHelper {
    constructor(baseURL) {
        this.baseURL = baseURL;
        this.token = null;
    }

    setToken(token) {
        this.token = token;
    }

    getToken(username, password) {
        var url = this.baseURL + `/token/${username}/${password}`;
        fetch(url, {
            method: "GET",
            header: {
                "Content-Type": "application/json"
            }).then(response => response.json())
            .then((data) => {
                this.setToken(data["access_token"]);
            });
    }

    getRequest(endpoint) {
        fetch(this.baseUrl + endpoint, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + this.token
            }
        }).then(response => response.json())
        .then((data) => {
            console.log(data);
        });
    }
}

这是我的App.js的简化版:

var apiHelper = new APIHelper("URLGoesHere");

class StarterApp extends React.Component {
  render() {
    apiHelper.getToken("UsernameGoesHere", "PasswordGoesHere");
    var users = apiHelper.getRequest("/users");
    console.log(users);
    return (
      //App Content Here
    );
  }
}

我尝试了许多不同的方法:使 API 调用异步,在 getRequest 函数中进行检查以等待 token 不是 null 但这似乎挂起,移动调用进入应用程序的构造函数。我想做的事可能吗?还是每次我想要调用 API 时都需要调用以获取令牌?

另外:我知道这不是一个特别安全的 API,它是一个学校项目的临时系统,请不要就此提供反馈。

【问题讨论】:

  • 从函数返回每个 fetch 调用,然后使用 async render()await apiHelper.getToken(...),因此下一行将仅在 fetch 完成后运行。
  • 我已经尝试过了,但 React Native 似乎不喜欢 render()async
  • 对,你不应该在render() 中这样做。在componentDidMount() 中执行此操作,然后相应地设置状态。

标签: javascript reactjs react-native


【解决方案1】:

如果您返回来自 getRequest 的承诺的 fetch 调用,getToken 您可以使用 await 确保对 getToken 的调用在 getRequest 之前完成。还按照 Chris G 的建议运行 componentDidMount 中的代码,例如

export class APIHelper {
constructor(baseURL) {
    this.baseURL = baseURL;
    this.token = null;
}

setToken(token) {
    this.token = token;
}

getToken(username, password) {
    var url = this.baseURL + `/token/${username}/${password}`;
    return fetch(url, {
        method: "GET",
        header: {
            "Content-Type": "application/json"
        }).then(response => response.json())
        .then((data) => {
            this.setToken(data["access_token"]);
        });
}

getRequest(endpoint) {
    return fetch(this.baseUrl + endpoint, {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + this.token
        }
    }).then(response => response.json())
    .then((data) => {
        console.log(data);
    });
}
}

var apiHelper = new APIHelper("URLGoesHere");

class StarterApp extends React.Component {
    async componentDidMount() {
        try {
            await apiHelper.getToken("UsernameGoesHere", "PasswordGoesHere");
            await var users = apiHelper.getRequest("/users");
            console.log(users);
        } catch (e) {
            console.log(e)
        }
    }
    render() {
        return (
            //App Content Here
        );
    }
}

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 2018-02-17
    • 2019-03-25
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多