简体   繁体   English

React-Native:如何在另一个类中获取API调用的回调

[英]React-Native : How to get callback of api call in another class

I am calling a web service 我正在打电话给网络服务

Here is my code: 这是我的代码:

var result;
export function callPostApi(urlStr, params)
{
       fetch(urlStr, {method: "POST", headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(params)})
            .then((response) => response.json())
            .then((responseData) => {
              result = JSON.stringify(responseData)
             })
            .catch((error) => { console.error(error);

             Alert.alert('Alert Title failure' + JSON.stringify(error))
            })
            .done();
          return result
}

I am calling from here: 我从这里打电话:

callapi(){
     var dict = {
          email: 'at@gmail.com',
          password: '123456',
        }
    result = callPostApi('http://demo.com', dict)
}

Currently, it is calling in Async mode that we want but code is written below this method getting execute immediately after calling of above method 当前,我们希望以异步模式进行调用,但是代码被编写在此方法下,并在调用上述方法后立即执行

i want callback when result from sever has received so that i can execute code written below the above method is execute after receiving response from server. 我希望在收到来自服务器的结果时进行回调,以便我可以执行以下方法编写的代码,这些代码是在收到服务器的响应后执行的。

You need to use Promises. 您需要使用Promises。

Change your callPostApi function to return a Promise, then you can chain additional then , catch and finally calls. 更改您的callPostApi函数以返回Promise,然后可以链接其他thencatchfinally调用。

export function callPostApi(urlStr, params) {
    return fetch(urlStr, {
            method: "POST", 
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(params)
        })
        .then((response) => response.json())
        .then((responseData) => {
            result = JSON.stringify(responseData)
        })
        .catch((error) => { 
            console.error(error);
            Alert.alert('Alert Title failure' + JSON.stringify(error))
        });
}


callapi() {
    callPostApi('http://demo.com', {
            email: 'at@gmail.com',
            password: '123456',
        })
        .then((response) => {
            // Continue your code here...
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM