0

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?

Community
  • 1
  • 1
xaander1
  • 612
  • 6
  • 24

2 Answers2

1

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);
Roy Ryando
  • 518
  • 8
  • 19
  • i just replaced your code with mine. **Gives:** `Promise {}` `undefined` `undefined` – xaander1 Dec 03 '19 at 06:54
  • maybe the `fetch` function itselft returning undefined , I cant make sure, where is the fetch function go? is it a public library or you created it? – Roy Ryando Dec 03 '19 at 07:00
  • its a local file i created...i don't think the fetch is returning undifined...you try it and see for yourself – xaander1 Dec 03 '19 at 07:02
  • please change alienMsg function with this and let me know the result `alienMsg(callback){ fetch('./file.txt').then((txt)=> callback(txt)); }` – Roy Ryando Dec 03 '19 at 07:06
  • **results:** `Response {}` – xaander1 Dec 03 '19 at 07:10
  • is this fetch function from ajax? I read from https://javascript.info/fetch ,how if you use `callback(txt.text())` ? – Roy Ryando Dec 03 '19 at 07:39
0

After continuous trying i temporally 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));
})();

xaander1
  • 612
  • 6
  • 24