简体   繁体   中英

How to access an object from another function in Javascript

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);
});

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.

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);
});

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();

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.

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);
});

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