I would like to know why the code works like this:
async function Signin({ email, pass, confirmpass }) {
const body = {
'email': email,
'pass': pass,
'confirmpass': confirmpass,
};
const params = {
endpoint: 'register_user',
method: 'post',
headers: null,
body: body
}
const result = await api.connect(params);
console.log(result);
}
but it doesn't work like this:
async function Signin({ email, pass, confirmpass }) {
let result = await registerUser({ email, pass, confirmpass, });
console.log(result);
// TODO: api call 2
// TODO: api call 3
}
async function registerUser({ email, pass, confirmpass }) {
const body = {
'email': email,
'pass': pass,
'confirmpass': confirmpass,
};
const params = {
endpoint: 'register_user',
method: 'post',
headers: null,
body: body
}
return api.connect(params);
}
It logs the following error: Possible Unhandled Promise Rejection
I have to make three calls to the api, so to make it more readable and easier to maintain I want to make the api calls in different functions.
I don't have much experience with JS Async/Await, I just started using it because I need to do something in React Native, I was from PHP before.
Update: I did like @safder said onj the comment and used try catch but now it doesn't wait the result
async function Signin({ email, pass, confirmpass }) {
try {
let result = await registerUser({ email, pass, confirmpass, });
console.log(result);
} catch {
}
// TODO: api call 2
// TODO: api call 3
}
async function registerUser({ email, pass, confirmpass }) {
let result = null;
const body = {
'email': email,
'pass': pass,
'confirmpass': confirmpass,
};
const params = {
endpoint: 'register_user',
method: 'post',
headers: null,
body: body
}
try {
result = api.connect(params);
} catch {
}
return result;
}
try ... catchblock or using.catch()to catch any potential errors.try/catch. You could justreturn api.connect(params)and keep thetry/catcharound the call site (let result = await registerUser)