简体   繁体   中英

Why do I need an explicit return when a Promise is returned?

I'm trying to understand this piece of code:

//Get local text file data
function getText() {
  fetch('test.txt')
    .then(function(res){
      return res.text(); //Question HERE!
    })
    .then(function(data) {
      console.log(data);
      document.getElementById('output').innerHTML = data;
    })
    .catch(function(err){
      console.log(err);
    });
}

In particular, I can't understand why I need to have return res.text(). Isn't the method text() returning already a Promise? So why do I need to explicitly return there? My idea is to get the Promise from the first .then and treat the latter witht the second then. But withoout that return, my variable data is logged as undefined.

res.data() does return a promise, but if you simply leave it there it will be function existing in its own scope with no purpose. When you return that function, you can chain it to the next then .

Update - Expanding on the res.text()

res.text() is doing the following inside:

return new Promise((resolve, reject) => {
  // Do something with your data and then
  resolve(data)
})

Now, when you call res.text() , that is the value you receive back: a Promise object in the pending state. The Promise object is what you chain then and catch to. But if you don't return the Promise, your function will create a Promise but return nothing . So when you use .then , it tries to connect to undefined , which is the value function returned.

So, essentially what you're doing there is:

function getText() {
  fetch('test.txt')
    .then(function(res){
      const promise = res.text();
      return promise;
    })
    .then(function(data) {
      console.log(data);
      document.getElementById('output').innerHTML = data;
    })
    .catch(function(err){
      console.log(err);
    });
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM