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
CodePudding user response:
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()
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()
CodePudding user response:
I strongly recommend you to use not async but Promise if you want to be good at JavaScript.
Promise is an expression that has a strong algebraic structure, and async-await, on the other hand, they are statements that has complicated rules.
CodePudding user response:
Hi!
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!
CodePudding user response:
Ok I figured it out:
async function foo() {
return setTimeout(() => {
console.log("foo")
}, 1000);
}
async function bar() {
return setTimeout(() => {
console.log("bar")
}, 1500);
}
foo()
bar()