Skip to content

Still a Promise #3808

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Bosquejo inicial- probar- ojo necesita agregar codigo a sol1, 2
  • Loading branch information
joaquinelio committed Nov 6, 2024
commit 5ef6ae170db2cfd8f307e4ba5d28d4d4e9f0a07f
23 changes: 23 additions & 0 deletions 1-js/11-async/08-async-await/04-still-a-promise/solution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

You may be tempted to take the lazy, slow, boring pseudo-synchronous way.

It's ok...

```js run


async function showTimes() {
const time1 = await babieca.run();
alert(time1);

const time2 = await rocinante.run();
alert(time2);

const time3 = await belcebu.run();
alert(time3);
}

```

No much fun.
There is a better way. Use the promise API
28 changes: 28 additions & 0 deletions 1-js/11-async/08-async-await/04-still-a-promise/solution2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

Let's race!

```js run


async function race() {
const results = await Promise.all([
babieca.run(),
rocinante.run(),
belcebu.run()
]);

alert("All the horses reached the goal! 🎉🏇\n" + results.join('\n'));
}

race();

```

This has no cost for your code. The horses run simultaneously. You may see when they are arriving in your console.


Please note: if you only care for the fastest horse, you may use `promise.any` so you dont even need to wait for the slower ones

const fastest = await Promise.any([babieca.run(), rocinante.run(), belcebu.run()]);
alert(`The winner: ${fastest}`);

28 changes: 28 additions & 0 deletions 1-js/11-async/08-async-await/04-still-a-promise/task.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

# Still a promise

Make the horses run then show their times

```js

class Horse {
constructor(name) {
this.name = name;
}

async run() {
const time = Math.floor(Math.random() * 3) + 1;

await new Promise(resolve => setTimeout(resolve, time * 1000));

const result = `${time * 20} segundos para ${this.name}!!! `;
console.log(result);
return result;
}
}

const babieca = new Horse('Babieca');
const rocinante = new Horse('Rocinante');
const belcebu = new Horse('Belcebú');

```