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);
});
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
sk123
  • 580
  • 1
  • 8
  • 29

5 Answers5

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.

Carlos Morales
  • 5,676
  • 4
  • 34
  • 42
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);
});
amitdigga
  • 6,550
  • 4
  • 26
  • 31
  • I just want to use `messageData` in some other function. I don't wanna called the 'getNotifications()` – sk123 Apr 29 '19 at 13:29
  • https://stackoverflow.com/questions/944273/how-to-declare-a-global-variable-in-a-js-file Check this out.. I think you can use message data where ever you want in .js file. – amitdigga Apr 29 '19 at 13:33
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();
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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.

iliasse
  • 247
  • 1
  • 7
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);
});
El.
  • 1,217
  • 1
  • 13
  • 23