How can i return a value to the function that called the asynchronous code and not the next then?
For demonstration purposes i wrote the following snippet to demonstrate my problem.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js"></script>
</body>
</html>
script.js
class fetchDemo{
constructor(dummy){
this.dummy=dummy
let msg= this.alienMsg();
console.log(msg);
}
alienMsg(){
fetch('./file.txt')
.then(response => response.text())
.then(body =>{
console.log(body);
return body;
})
.then((txt)=>{
console.log(txt)
});
}
}
new fetchDemo(null);
file.txt
I am on a mission to invade earth
When you run this however you get
undefined
I am on a mission to invade earth
I am on a mission to invade earth
How do i return so that msg
also logs I am on a mission to invade earth
and not undifined
?