【问题标题】:How to access an object from another function in Javascript如何从 Javascript 中的另一个函数访问对象
【发布时间】:2019-04-29 13:15:40
【问题描述】:

我正在尝试从数组中获取一些数据并将其存储在一个对象中,但我一直在日志中获取一个空对象或Promise { <pending> }。我正在使用global 变量来存储它并在另一个函数中访问它。不知道我做错了什么。

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

【问题讨论】:

  • messageData = notificationData;似乎您将某些值准确地设置为变量..确保它是对象...或设置 my, messageData['key'] = value
  • 查看我的更新答案

标签: javascript node.js object


【解决方案1】:

控制台日志在异步方法/Promise 被解析之前发生。你应该在那之后检查它。换句话说,您的代码应该类似于:

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

如果您不想在 getNotifications() 中调用它,只需获取它返回的 Promise 并在 .then()(选项 1)中执行您的调用,或者执行 await(选项 2)。在代码中:

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

了解更多https://javascript.info/async 主题的链接。

【讨论】:

    【解决方案2】:

    逐行解码你的程序

    var messageData = {};
    

    是一个对象

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

    getNotifications 是一个异步函数。

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

    getMessageData 打印任何消息数据。

    getMessageData(); 
    

    您打印了{} 的消息数据。请记住 getNotfications 直到现在才被调用,因为行是被一一执行的。

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

    现在上面的代码调用getNotification并在异步调用完成时运行then中提供的function。所以你需要在 then 函数中调用getMessageData()

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

    【讨论】:

    • 我只想在其他一些功能中使用messageData。我不想调用 'getNotifications()`
    • stackoverflow.com/questions/944273/… 看看这个。我认为您可以在 .js 文件中的任何位置使用消息数据。
    【解决方案3】:

    您在getNotifications 之前执行getMessageData。您可以使用 async/await 方法

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

    【讨论】:

      【解决方案4】:

      您需要等待 getNotifications 函数完成,然后才能将其结果记录到控制台。

      getNotifications 是异步的,这意味着它不会同步运行以下代码行

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

      可能在您的 getNotifications 完成之前执行,因此您的 getMessageData() 调用不会打印想要的结果。

      【讨论】:

        【解决方案5】:

        首先:在这种情况下,您的全局变量 messageData 将成为 fcmObjects 中的最后一项。所以请确保在fcmObjects.forEach( (notificationData) => { messageData = notificationData; }); 中为messageData 对象提供键或索引 第二: 当您调用 Asynchronous 操作时,您不会以这种方式记录它。

        毕竟你的代码一定是这样的:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-14
          • 2022-01-02
          • 1970-01-01
          • 2019-06-29
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          相关资源
          最近更新 更多