How to do asynchronous tasks like this:
I want to have two tasks: One would print "foo" after 1 second, and the other one would print "bar" after 2 seconds. I want them to start at the same time, and run asynchronously.
Here's an example of this in python:
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
print(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
How do I do something like this in JavaScript? Do I use promises? I don't know how they work. I'm "new" to javascript
You can use then method of js promises.
function timeout(time_ms) {
return new Promise(resolve => setTimeout(resolve, time_ms));
}
function main() {
timeout(1000).then(() => console.log("hello"))
timeout(2000).then(() => console.log("world"))
var d = new Date();
var n = d.toLocaleTimeString();
console.log(`started at ${n}`)
}
main()
You can do it like this:
async function hello() {
setTimeout(() => {}, 1000)
console.log("hello")
}
async function world() {
setTimeout(() => {}, 2000)
console.log("world")
}
async function main() {
await hello()
await world()
}
main()
Let me know if that works for you!