How do I wait for the response of one function in another?

  • 0
    DD, there's a fetch request that the city receives.
    fetch(url + query, options)
                        .then(response => response.json())
                        .then(data => this.currentCity =
                        .catch(error => console.error(error))

    and there is another request that receives the weather in this option.
                        .then(response => response.json())
                        .then(data => this.weatherResult = data)

    the problem is that undefined is stored in this.currentCity at the time of the fetch request, and as a result, there is an error in the request because the location is not defined, how can I wait for the result of the first fetch and then execute the second request? I suppose async / await is helpful, but I don’t understand how to rewrite
    JavaScript Anonymous, Apr 30, 2020

  • 1 Answers
  • 0
    this.weatherResult = await fetch(url + query, options)
    .then(response => response.json())
    .then(data =>
    .then(currentCity => fetch(`${this.base_url}weather?q=${currentCity}&units=metric&APPID=${this.api_key}`))
    .then(response => response.json())


    const firstResponse = await fetch(url + query, options);
    const data = await firstResponse.json();
    const currentCity =;
    const secondResponse = await fetch(`${this.base_url}weather?q=${currentCity}&units=metric&APPID=${this.api_key}`);
    this.weatherResult = await secondResponse.json();
    Eden Flores

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!