Reputation: 10828
I am learning how to use class
with Async/Await. I think I am doing something wrong with getData
function in the Run
class.
It should output "Hello World" when using await get()
(experiment).
When I run the script, I get an error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
Class Script:
class Run {
constructor() {
this.stop = false;
}
async getData(entry) {
if (this.stop) {
console.log("Stopped")
return;
}
return await this.get();
}
async get() {
return "Hello World";
}
stop() {
this.stop = true;
}
}
Usage:
let run = new Run();
run.getData(async (entry) => {
console.log(entry);
});
Upvotes: 0
Views: 54
Reputation: 15079
Your original code refer to the other methods, not the one in your class:
async getData(entry) {
if (stop) { // <--- this refers to this.stop() method
console.log("Stopped")
return;
}
return await get(); <--- this doesn't refer to your `this.get()` method
}
So, add this.
to fix it at above two positions.
Upvotes: 0
Reputation: 60347
You're getting an error because you forgot the this
qualifier:
async getData(entry) {
if (this.stop) {
^^^^
Using return await
only makes sense, when you use it within a try/catch block. Otherwise, it is completely redundant.
You should use it here instead. Also, getData
does not use its parameter entry
. You should call it directly:
console.log(await run.getData());
^^^^^
Upvotes: 1