简体   繁体   中英

Storing result from API call to JavaScript array

I'm having trouble storing the result from this fetch to an array:

const words = []
fetch("https://random-word-api.herokuapp.com/word?number=100")
  .then(response => response.text())
  .then(result => console.log(result))
  .then(function (data) {
    for (var i = 0; i < result.length; i++) {
      words.push(data.result[i])
      console.log(words)
    }
  })
  .catch(error => console.log('error', error));
let promise = fetch("https://random-word-api.herokuapp.com//word?number=10")

Firstly you want to call response.json() instead since the data returned is json
The data is in the result parameter after, you can iterate through this array to get the words.

 const words = [] fetch("https://random-word-api.herokuapp.com/word?number=100").then(response => response.json()).then(function (result) { console.log('Result', result) for (var i = 0; i < result.length; i++) { words.push(result[i]) } console.log('Words', words) }).catch(error => console.log('error', error));

The way you're planning on storing the words array might be problematic because you can't control how long the fetch will take.
Usually you'd store the result of the promise in a variable an control that after the promise has settled:

 const words = fetch("https://random-word-api.herokuapp.com/word?number=100").then(response => response.json()) words.then(x => { console.log('the promise has settled', x) }).catch(console.error)

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