B
B
bernex2017-01-27 08:04:13
Node.js
bernex, 2017-01-27 08:04:13

How to make async/await output to a file in the correct order?

let data = {cat:1,dog:2};
Object.keys(data).map(async (id) => {
                await  appendFile(fileName, id);
                await  appendFile(fileName, data[id]);
        });

out: catdog12
But i want:
cat1dog2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2017-01-27
@bingo347

async function saveData(data) {
  for(let id of Object.keys(data)) {
    await  appendFile(fileName, id);
    await  appendFile(fileName, data[id]);
  }
}

saveData({cat:1,dog:2})

As an option, for sequential execution, solve the problem purely on promises:
let data = {cat:1,dog:2};
Object.keys(data).reduce(
  (p, id) => p
    .then(() => appendFile(fileName, id))
    .then(() => appendFile(fileName, data[id])),
  Promise.resolve()
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question