Created
September 5, 2018 11:43
-
-
Save Wikiko/27136644037b689e8ebf999d94735f5b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Exemplo "iscoolapp" não lembro qual ecmascript usa ai acho que es5. | |
function fetchUser(id) { | |
//busca o user pelo id, isso é um mock ok. | |
return Promise.resolve({ id: id, name: 'user', role: 'admin' }); | |
} | |
function fetchUserAddress(id) { | |
return Promise.resolve({ | |
userId: id, | |
rua: 'Carpinteiro', | |
bairro: 'Warner Plass', | |
cidade: 'Americana' | |
}); | |
} | |
function doFetches() { | |
const userId = 1; | |
//Para fazer em paralelo as requests. | |
Promise | |
.all([fetchUser(userId), fetchUserAddress(userId)]) | |
.then(requests => { | |
const user = requests[0]; | |
const userAddress = requests[1]; | |
// usa as variaveis pra o que quiser... | |
}); | |
} | |
// Exemplo ES6 | |
const fetchUser = id => Promise.resolve({ id, name: 'user', role: 'admin' }); | |
const fetchUserAddress = id => Promise.resolve({ | |
userId: id, | |
rua: 'Carpinteiro', | |
bairro: 'Warner Plass', | |
cidade: 'Americana' | |
}); | |
const doFetches = () => { | |
const userId = 1; | |
Promise | |
.all([fetchUser(userId), fetchUserAddress(userId)]) | |
.then(([user, userAdress]) => { | |
//Usa aqui as variaveis... | |
}); | |
} | |
// EXEMPLO ES7 A COISA LINDAAAAA QUE USO. | |
// nesses blocos de consulta da pra usar o promise normal... | |
// toda atualização é compativel com os anteriores nada quebra. | |
const fetchUser = async (id) => ({ id, name: 'user', role: 'admin' }); | |
const fetchUserAddress = async (id) => ({ | |
userId: id, | |
rua: 'Carpinteiro', | |
bairro: 'Warner Plass', | |
cidade: 'Americana' | |
}); | |
const doFetches = async () => { | |
const userId = 1; | |
const [user, userAddress] = await Promise.all([fetchUser(userId), fetchUserAddress(userId)]); | |
// usa as variaveis aqui... sim parece sincrono mas o await faz a magia negra kkkk. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment