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
?
JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.
Try using callback function
class fetchDemo{ constructor(dummy){ this.dummy=dummy; this.alienMsg(function(data) { console.log(data); }); } alienMsg(callback){ fetch('./file.txt') .then(response => callback(response.text())) .then(body =>{ callback(body); }) .then((txt)=>{ callback(txt); }); } } new fetchDemo(null);
After continuous trying i temporarily solved the problem using JavaScript promises
However am not going to mark my answer as correct
NB: I had to ditch using JavaScript classes
var alienMsg = new Promise(
(res,rej)=>{
fetch('./file.txt')
.then(response => response.text())
.then(body =>{
//console.log(body);
return body;
})
.then((txt)=>{
//returning inside then using JavaScript promises resolve
res(txt)
});
}
);
(()=>{
alienMsg
.then(data=> console.log(data));
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.