Javascript async for python programmers
Coming from python side, I’ve always been tortured by the different variations of javascript. What is ‘use strict’ exactly? Why are there import * but also require? Why are there so many functions?!
So in this article we will:
- Explain some concepts for javascript: promise, await, async, callback
- Loop an array asynchronously to get response
promise
await with Promise
- Create a function which returns a promise
- Use await with this function
- They can be used inside an async function
function scaryClown() {
return new Promise(resolve => {
setTimeout(() => {
resolve('🤡');
}, 2000);
});
}
async function msg() {
const msg = await scaryClown();
console.log('Message:', msg);
}
msg(); // Message: 🤡 <-- after 2 seconds
https://alligator.io/js/async-functions/
async
Asynchronous functions always returns promises
const functionName = async (arguments) => {
// Do something asynchronous
}
callback
Loop an array with map of async functions
const list = [] //...an array filled with values
const functionWithPromise = item => { //a function that returns a promise
return Promise.resolve('ok')
}
const anAsyncFunction = async item => {
return await functionWithPromise(item)
}
const getData = async () => {
return await Promise.all(list.map(item => anAsyncFunction(item)))
}
const data = getData()
console.log(data)
What if we want to do some processing about the returned results of the promises? I was first trying to do something with the promise, until I realised it’s not gonna work at all.
At last the solution I found is like this:
- Create an async function, which returns a promise.
2. Use map to loop through an array using the async function created above, this will create an array of promises.
3. Use Promise.all to get the objects stored in the promises, and do processing on it.