A typical example of the fetch, which is full of Google (specifically this one with the habr):

fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'}) .then(function(response) { return response.text(); }) .then(function(text) { console.log('Request successful', text); }) .catch(function(error) { log('Request failed', error) }); 

But how to get access to the response from the second then ?

I, of course, can just push it into some external variable before return response.text() , but in general it looks somehow unreliable, because asynchronous, stupid user clicks the button twice, for example, some other response another request will be fantastic luck.

I would like to just transfer it further to the function, and, I suspect, we must somehow foster our promises, but I'm still not cool enough to pile them up on my own, I'm afraid to mess things up.

  • And if to transfer return as object simply? - dimaua
  • @dimaua or I did not understand something, or not, response.text() is a promise and I also need to somehow get the result - andreymal
  • That is, return {text: response.text (), response: response} does not work? - dimaua
  • @dimaua is not, I will not get the result of promise - andreymal
  • so, why in the second then response? - Grundy

1 answer 1

You can immediately select the required fields and wait for them all together using Promise.all (if any of the elements of the array is not Promise , it will be automatically converted into it using Promise.resolve ):

 fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'}) .then(function(response) { return Promise.all([response.text(), /*что-то еще*/, /* что-то еще*/]); }) .then(function(array) { var text = array[0]; var /*что-то еще*/ = array[1]; var /* что-то еще*/ = array[2]; console.log('Request successful', text); }) .catch(function(error) { log('Request failed', error) }); 

Either it is even easier to do it: save the Promise you need, and make branches from it already

 var fetchResult = fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'}); fetchResult.then(function(response) { return response.text(); }).then(function(text) { console.log('Request successful', text); }); fetchResult.then(function(response) { return response.json(); }).then(function(json) { console.log('Request successful', json); }); 
  • But it looks good. But since I have already forgotten in a few months why I needed it specifically, I will comment on / mark the answer later) - andreymal
  • Hmm, but the response itself is no longer promis, but a completely ready-made variable and there’s nothing to wait for, I can’t just take it and stuff it instead of /* что-то еще */ ? - andreymal
  • @andreymal, I did not understand the question - Grundy
  • What should I write instead of /* что-то еще */ , so that in the second then get access to the response? - andreymal
  • one
    @andreymal, so write response - Grundy