Answer the question
In order to leave comments, you need to log in
Why can't I use await in an if block?
Hello everyone
There is such an AC:
export const renderNotes = (user , users) => async dispatch => {
Object.keys(users).map(element => {
if (user === users[element].login) {
let elements = await fire.database().ref('users/' + element + '/notes/'); // Сейчас тут ошибка
return dispatch({
type: RENDER_NOTES,
payload: elements
})
}
})
};
export const renderNotes = (user , users) => async dispatch => {
let elements = await fire.database().ref('users/' + element + '/notes/'); // Вынес сюда присвоение
Object.keys(users).map(element => {
if (user === users[element].login) {
return dispatch({
type: RENDER_NOTES,
payload: elements
})
}
})
};
Answer the question
In order to leave comments, you need to log in
The point is not in the conditional operator, but in the fact that your map callback is not an asynchronous function and you cannot use the await keyword in it . You can fix it like this:
export const renderNotes = (user , users) => dispatch => {
Object.keys(users).forEach(async element => {
if (user === users[element].login) {
const elements = await fire.database().ref('users/' + element + '/notes/');
return dispatch({
type: RENDER_NOTES,
payload: elements,
});
}
})
};
const srcArray = [ 0.134555, 0.294587, 0.570858];
const mappedArray = srcArray.map(el => (el * 100).toFixed(1) + '%');
console.log(mappedArray);
// => ["13.5%", "29.5%", "57.1%"]
In order to use await, there must be a Promise object in the structure as described in the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaS...
try this
export const renderNotes = async(user , users) => async dispatch => {
let elements = await fire.database().ref('users/' + element + '/notes/'); // Вынес сюда присвоение
Object.keys(users).map(element => {
if (user === users[element].login) {
return dispatch({
type: RENDER_NOTES,
payload: elements
})
}
})
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question