Reputation: 197
I'm to get my head around async
/await
but having trouble getting the steps inside the function to run sequentially, and wait for each other to finish.
Basically I'm trying to get it to fire off myProm
, wait a second, fire it off again.
What am I not getting?
function myProm() {
return new Promise((resolve, reject) => {
resolve(setTimeout(() => {
console.log('promise in one seconds');
}, 1000))
})
}
async function myFunc() {
try {
await myProm();
await myProm();
}
catch(error) {
console.log(error)
}
}
myFunc()
Upvotes: 3
Views: 95
Reputation: 887355
Your myProm
function's promise calls resolve()
immediately, so it doesn't actually wait for anything.
You need to only call resolve()
once you want your promise to resolve (inside the callback).
Upvotes: 1
Reputation: 1074168
You're calling resolve
right away. You should do it inside the setTimeout
callback:
function myProm() {
return new Promise((resolve, reject) => {
console.log('promise in one seconds');
setTimeout(() => {
resolve();
}, 1000);
})
}
(Or the setTimeout
could be setTimeout(resolve, 1000)
if you just want to call resolve.)
Live Example:
function myProm() {
return new Promise((resolve, reject) => {
console.log('promise in one seconds');
setTimeout(() => {
console.log('resolved');
resolve();
}, 1000);
})
}
async function myFunc() {
try {
await myProm();
await myProm();
}
catch(error) {
console.log(error)
}
}
myFunc();
Upvotes: 3