asyn c / жду не дождусь ответа - PullRequest
0 голосов
/ 05 марта 2020

Я запрашиваю API, используя POST метод. но после вызова функции RemoteRequest с помощью await. Это не ждет ответа ответа. Он непосредственно выполняет оставшийся код в register.js, получая status = undefind в регистре console.log.

. js

const DeviceUniqueId = DeviceInfo.getUniqueId();
const requestBody = { phone: phone, username: username };
const status = await RemoteRequest(URLs.APP_REGISTER, 
'POST', DeviceUniqueId, requestBody);

console.log('status====>', status);
this.setState({
    loading : false
});

remotereuqest. js

export const RemoteRequest = async (url, method, DeviceUniqueId, requestbody) => {
    console.log(url, method, DeviceUniqueId, requestbody);

    NetInfo.fetch().then((state) => {
        if (state.isConnected) {
            fetch(url, {
                method  : method,
                headers : {
                    Accept           : 'application/json',
                    'Content-Type'   : 'application/json',
                    DEVICEID         : DeviceUniqueId,
                    'Accept-Charset' : 'utf-8'
                },
                body    : JSON.stringify(requestbody)
            })
                .then((response) => {
                    console.log('reponse=====>', response);
                    return response.json();
                })
                .then((responseData) => {
                    console.log(responseData);
                    if (responseData.status == 'OK' && responseData.code == 200) {
                        return responseData.code;
                    }
                    return null;
                })
                .catch((error) => {
                    console.log(error);
                    if (error.message == 'Network request failed') {
                        showMessage({
                            floating        : true,
                            message         : 'Connection error',
                            description     : 'you have no Internet Connection',
                            type            : 'alert',
                            backgroundColor : 'red'
                        });
                        return null; //503
                    }
                    else {
                        showMessage({
                            floating        : true,
                            message         : 'Internal Server Error',
                            description     : 'please try again after some time',
                            type            : 'alert',
                            backgroundColor : 'red'
                        });
                        throw error;
                        return null;
                    }
                })
                .done();
        }
        else {
            showMessage({
                floating        : true,
                message         : 'Connection error',
                description     : 'you have no Internet Connection',
                type            : 'alert',
                backgroundColor : 'red'
            });
            return null; //503
        }
    });
};

Ответы [ 2 ]

0 голосов
/ 05 марта 2020

Когда вы используете .then () код после его немедленного выполнения, поэтому вместо этого вы должны дождаться ответов и затем выполнить работу без .then () - s.

const state = await NetInfo.fetch();
if (state.isConnected) {
  const response = fetch(url, ...);
  console.log(response);
  ...
}
0 голосов
/ 05 марта 2020

Вам нужно дождаться всех обещаний внутри функции, в противном случае они все равно будут выполняться асинхронно. Как то так:

await NetInfo.fetch().then( async (state) => {
    if (state.isConnected) {
        await fetch(url, { 
        ...
        }
    }
});
...