Skip to content

Instantly share code, notes, and snippets.

@Woodsphreaker
Created October 4, 2017 04:56
Show Gist options
  • Save Woodsphreaker/af97f3f2be0c3f6cadf7f0e60bba9dd6 to your computer and use it in GitHub Desktop.
Save Woodsphreaker/af97f3f2be0c3f6cadf7f0e60bba9dd6 to your computer and use it in GitHub Desktop.
services async - (async / await)
const obj = [{
nome: "User1",
cpf: "000.000.000-00",
time: 1000,
result: 0
},
{
nome: "User2",
cpf: "111.000.000-00",
time: 1200,
result: 0
},
{
nome: "User3",
cpf: "222.000.000-00",
time: 1400,
result: 0
},
{
nome: "User4",
cpf: "333.000.000-00",
time: 1600,
result: 0
},
{
nome: "User5",
cpf: "444.000.000-00",
time: 1800,
result: 0
}]
const timeDelay = (nome, time = 1000) => {
return new Promise(resolve => {
setTimeout(() => resolve(`Process ${nome} in ${time} ms`), time)
})
}
const processData = async el => {
return {
nome: el.nome,
cpf: el.cpf,
result: await (timeDelay(el.nome, el.time))
}
}
const asyncMethod2 = data => {
const results = data.map(processData)
return Promise.all(results)
}
asyncMethod2(obj)
.then(res => console.log(res))
/*
[ { nome: 'User1',
cpf: '000.000.000-00',
result: 'Process User1 in 1000 ms' },
{ nome: 'User2',
cpf: '111.000.000-00',
result: 'Process User2 in 1200 ms' },
{ nome: 'User3',
cpf: '222.000.000-00',
result: 'Process User3 in 1400 ms' },
{ nome: 'User4',
cpf: '333.000.000-00',
result: 'Process User4 in 1600 ms' },
{ nome: 'User5',
cpf: '444.000.000-00',
result: 'Process User5 in 1800 ms' } ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment