Home > Net >  Getting Promise Data in Javascript
Getting Promise Data in Javascript

Time:11-26

This question has been asked many times but after reading all the responses, mine still doesn't work and I think it has something to do with the scope of the variable.

I am trying to make a request and return it's result back into the main scope but it either returns undefined or a promise even though the promise has already been fulfilled.

const getLastMessage = fetch("/history?id=" getChatID())
  .then((response) => response.json())
  .then((messages) => {
    return messages[messages.length-1]['id']
    // returns correct result
  })

const getLastFetched = async () => {
  lastMessage = await getLastMessage
  // sets lastMessage to correct value
};

let lastMessage = getLastFetched()
console.log(lastMessage)
// undefined

If I make getLastFetched return data to lastMessage it will return a promise object. I tried this exact same thing previously and it worked?

CodePudding user response:

Use Javascript load event

window.addEventListener("load", async (event) => {
   let lastMessage = await getLastFetched()
});

CodePudding user response:

Assuming you are running the code in async block, you should add await before getLastFetched(). Also, that will return an empty promise because getLastFetched doesn't return anything. So even if last message will get declared, id doesn't matter because at the time of console log it's empty. The last thing is, lastMessage should be declared before getLastFetched.

const getLastMessage = fetch("/history?id=" getChatID())
  .then((response) => response.json())
  .then((messages) => {
    return messages[messages.length-1]['id']
    // returns correct result
  })

let lastMessage;

const getLastFetched = async () => {
  lastMessage = await getLastMessage
  // sets lastMessage to correct value
};

await getLastFetched()
console.log(lastMessage)

This is how it would work inside of async IIFE block:

(async () => {
  const getLastMessage = fetch("/history?id=" getChatID())
    .then((response) => response.json())
    .then((messages) => messages[messages.length-1].id);

  let lastMessage;

  const getLastFetched = async () => {
    lastMessage = await getLastMessage
    // sets lastMessage to correct value
  };
    
  await getLastFetched()

  console.log(lastMessage);
})();
  • Related