2

I'm trying to get some data from an array and store store it in an object but I keep getting either an empty object or Promise { <pending> } in the logs. I'm using a global variable to store it and access it in another function. Not sure what i'm doing wrong.

var messageData = {};

const getNotifications =  async () => {
    let fcmObjects = await fcmTokens();
    fcmObjects.forEach( (notificationData) => {
        messageData = notificationData;
    });
};

function getMessageData() {
    console.log(messageData);
}

getMessageData();

getNotifications().then(function () {
    console.log('All Done');
}).catch(function (error) {
    console.log('Oops', error);
});
2
  • messageData = notificationData; seems you exactly setting some value into variable.. ensure its is object... or set my, messageData['key'] = value Commented Apr 29, 2019 at 13:18
  • checkout my updated answer Commented Apr 29, 2019 at 13:37

5 Answers 5

2

the console log is happening before the async method/Promise is being resolved. You should check it only after that. In other words, your code should be similar to:

getNotifications().then(function () {
    getMessageData();
    console.log('All Done');
}).catch(function (error) {
    console.log('Oops', error);
});

If you do not want to call it inside getNotifications(), just get the Promise it returns and execute your call inside the .then() (option 1) or do an await (option 2). In code:

const notificationPromise = getNotifications();
// option 1
notificationPromise.then(getMessageData);
// option 2
await notificationPromise;
getMessageData();

A link to know more https://javascript.info/async about the topic.

Sign up to request clarification or add additional context in comments.

Comments

0

Decoding your program line by line

var messageData = {};

is an object

const getNotifications =  async () => {
    let fcmObjects = await fcmTokens();
    fcmObjects.forEach( (notificationData) => {
        messageData = notificationData;
    });
};

getNotifications is an async function.

function getMessageData() {
    console.log(messageData);
}

getMessageData prints whatever is message data.

getMessageData(); 

you printed message data which is {}. Remember getNotfications is never called till now as the line are executed one by one.

getNotifications().then(function () {
    console.log('All Done');
}).catch(function (error) {
    console.log('Oops', error);
});

Now the above code call getNotification and run the function provided in then when the async call is completed. So you need to call getMessageData() in then function.

getNotifications().then(function () {
    getMessageData();
    console.log('All Done');
}).catch(function (error) {
    console.log('Oops', error);
});

2 Comments

I just want to use messageData in some other function. I don't wanna called the 'getNotifications()`
stackoverflow.com/questions/944273/… Check this out.. I think you can use message data where ever you want in .js file.
0

You execute getMessageData before getNotifications. You can use async/await approach

try {
  await getNotifications();
  getMessageData();
  console.log('All Done');
} catch (error) {
  console.log('Oops', error);
}

var messageData = [];

const getNotifications = async() => {
  //let fcmObjects = await fcmTokens();
  //fcmObjects.forEach((notificationData) => {
  //  messageData = notificationData;
  //});
  
  // simulate commentet above code
  return new Promise((resolve,reject)=>{ messageData=['someMessage']; resolve()})
};

function getMessageData() {
    console.log(messageData);
}

async function run() {
  try {
    await getNotifications();
    getMessageData();
    console.log('All Done');
  } catch (error) {
    console.log('Oops', error);
  }
}

run();

Comments

0

You need to wait the getNotifications function to finish before you could log it's result to the console.

getNotifications is asynchronous, which means it won't run synchronously and the following lines of code

function getMessageData() {
    console.log(messageData);
}

getMessageData();

may be executed before your getNotifications completes, thus your getMessageData() call doesn't print the wanted result.

Comments

0

First: your global variable messageData gonna be the last item in fcmObjects in this scenario. so make sure you provide a key or index for messageData object in fcmObjects.forEach( (notificationData) => { messageData = notificationData; }); Second: when you call an Asynchronous operation you would not log it that way.

After all your code must be like this:

var messageData = {};

const getNotifications =  async () => {
    let fcmObjects = await fcmTokens();
    fcmObjects.forEach( (index, notificationData) => {
        messageData[index] = notificationData;
    });
};

function getMessageData() {
    console.log(messageData);
}

getNotifications().then(function () {
    getMessageData();
    console.log('All Done');
}).catch(function (error) {
    console.log('Oops', error);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.