0

I want to use the data I get from a fetch request so I return it as an array. The return value(array) will be use to another function but I get a promise :

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(10)

Below is the complete code

function getEmailList() {
  fetch(myData.root_url + '/wp-json/wp/v2/email', {
    method: "GET",
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => {
    return response.json();
  }).then(emails => {
    emails.map((email) => {
      emailArr.push(email.title.rendered)
    })
    return emailArr;
  }).catch(err => console.log('failed', err))
}

function getData() {
  let emailList = getEmailList();
  console.log(emailList)
}
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
Monmon
  • 31
  • 4
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Oct 13 '20 at 02:02

3 Answers3

0

Use async await

function async getData() {
  let emailList = await getEmailList();
  console.log(emailList)
}
iamhuynq
  • 5,357
  • 1
  • 13
  • 36
0

Your calling code can be

function getData() {
  getEmailList().then(emailList => console.log(emailList));  
}
Oboo Cheng
  • 4,250
  • 3
  • 24
  • 29
Rain.To
  • 504
  • 2
  • 7
0

You need to return fetch in getEmailList() and use async/await in getData().

function getEmailList() {
  return fetch(myData.root_url + '/wp-json/wp/v2/email', {
    method: "GET",
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(response => {
    return response.json();
  }).then(emails => {
    emails.map((email) => {
      emailArr.push(email.title.rendered)
    })
    return emailArr;
  }).catch(err => console.log('failed', err))
}

async function getData() {
  let emailList = await getEmailList();
  console.log(emailList)
}
Ahmed ElMetwally
  • 2,276
  • 3
  • 10
  • 15