I'm new to javascript and I tried to implement my first async await and can't figure out where is my problem.
getName() - should return a promise after 1s. f() - should wait for getName to finish and then print name
What am I missing ?
const getName = async () => {
setTimeout(() => 'xxx', 1000)
};
const f = async () => {
name = await getName()
console.log(name)
}
f()
The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution. The code block below shows the use of Async Await together.
The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it's an error, an exception is generated — same as if throw error were called at that very place.
You need to place the loop in an async function, then you can use await and the loop stops the iteration until the promise we're awaiting resolves.
Unless you're using await
also inside getName
, you don't need to have getName
async, you just need to return a Promise
; since await
works with promises:
const getName = () =>
new Promise(resolve => setTimeout(resolve, 1000, 'xxx'));
async f() {
let name = await getName();
console.log(name);
}
f();
To await a function, that function must return a promise.
You thus need to create a new promise. It will have 2 methods: resolve
, and reject
.
resolve
returns the variable, and is used on success. You can catch its return value by using promise.then(value => )
or by await
ing it.reject
throws an error, and is used on error. You can catch the error by using promise.catch(err => )
or by awaiting the async function and wrapping it in a try-catch block.Here is how your code should look:
const getName = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('xxx');
}, 1000)
})
};
const f = async () => {
name = await getName()
console.log(name)
}
f()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With