N
N
Nikita Shchypylov2018-02-07 17:01:00
JavaScript
Nikita Shchypylov, 2018-02-07 17:01:00

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
      })
    }
  })
};

So - everything works:
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
      })
    }
  })
};

Why can't I use await in If() ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2018-02-07
@Nikulio

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,
      });
    }
  })
};

In the case when you just need to go through the elements of the array, it is wrong to use the map method , for such cases there is the forEach method .
map should be used when, based on the original array, you need to get a new array of elements transformed according to a certain algorithm:
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%"]

K
koshiii, 2018-02-07
@koshiii

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...

R
Roman Aleksandrovich, 2018-02-07
@RomReed

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 question

Ask a Question

731 491 924 answers to any question