жду не дожидаюсь JavaScript - PullRequest
0 голосов
/ 09 марта 2019

У меня есть следующий код:

var arrayAxios = [];
            
const array = async() => {
  await sleep(3000);
  _.forEach(tasks, task => {
    let res = _.includes("selected", task.value);
    if (res) {
      this.axios
        .get(url, { params: { data1 } })
        .then(response => {
          arrayAxios.push(this.axios.post(url, { dataAAA }));
        });
    }
  });
};
              
var promises = async() => {
  const arrayAxios = await array();
  await Promise.all(arrayAxios)
    .then(response => {
      resetAll_dataAAA();   // <--- my dataAAA in arrayAxios are reset before post in Promise.all!
    })
    .catch(error => {
      console.log(error);
    });
};

promises();

Функция resetAll_data () выполняется перед тем, как данные отправляются в DDBB. Я не могу найти проблему.

Есть предложения?

Большое спасибо!

Ответы [ 2 ]

1 голос
/ 09 марта 2019

Вы ищете

async function array() {
  await sleep(3000);
  var arrayAxios = []; // declare the array locally
  _.forEach(tasks, task => {
    let res = _.includes("selected", task.value);
    if (res) {
      arrayAxios.push(this.axios
//    ^^^^^^^^^^^^^^^ push to the array immediately, not asynchronously
        .get(url, { params: { data1 } })
        .then(response => {
          return this.axios.post(url, { dataAAA }));
//        ^^^^^^ chain the promises
        })
      );
    }
  });
  return arrayAxios;
//^^^^^^ give the result to the caller
}
0 голосов
/ 09 марта 2019

Я упростил ваш пример, чтобы вы, надеюсь, поняли, что происходит:)

Вам нужно вернуть массив обещаний из массива, чтобы иметь возможность разрешить их с помощью Promise.all

нет смысла использовать await Promise.all().then использовать await или then

массив никогда не возвращал обещание запроса, поэтому, когда его ожидали, он был бы решен немедленно

сон, я не верю, что это также функция в узле.

любые вопросы, дайте мне знать, рады помочь.

const axios = {
  get: async(task) => {
    return task.res;
  },
  post: async(task) => {
    return task;
  }
}

const tasks = [{url: 'getting', res: {got: 'got the thing', post: 'thing to post'}}, {url: 'getting 2', res: {got: 'got the thing 2', post: 'thing to post 2'}}]

const getRequest = async(url = '') => { 
  const res = await axios.get(url)
  console.log(res.got)
  return postRequest(res.post)
}

const postRequest = async (url = '') => {
  const res = await axios.post(url)
  console.log(res)
  return res;
}

const array = async() => {
  const createRequests = async task => {
    return getRequest(task)
  }

  return tasks.map(createRequests).filter(Boolean);
};

const promises = async() => {
  console.log('waiting')
  const res = await array()
  const all = await Promise.all(res)
  console.log('awaited')
  console.log('can call your reset')
};

promises();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...