1

This code is definitely wrong, but I'm not sure how to fix it.

E.g.

fetch('api/foo?get_max=True')
    .then( function(response) {
        return response.json();
    }
    .then( function(response) {
        var max = response["max"];
    }

fetch('api2/bar?max=' + max)
    .then( function(response) {
        return response.json();
    }
    .then( function(mydata) {
        processdata(mydata);
    }

This obviously doesn't work, because the max var that will eventually be defined in the first fetch does not yet exist when the second fetch runs. How can I "chain" or force the second fetch to "wait" for the first fetch?

senorsmile
  • 740
  • 8
  • 19

1 Answers1

4

Since fetch() returns a promise you can return it from a then() and it will behave as expected:

fetch('api/foo?get_max=True')
.then( response => response.json())
.then( response => {
    var max = response["max"];
    return fetch('api2/bar?max=' + max)
})
.then( response => response.json())
.then( mydata => processdata(mydata))
Mark
  • 90,562
  • 7
  • 108
  • 148