【问题标题】:parameter of the anonymous function need to be modified and stored in a global variable in javascript匿名函数的参数需要修改并存储在javascript中的全局变量中
【发布时间】:2013-05-15 19:44:05
【问题描述】:

如何获取匿名函数返回的值,该值用作另一个 javascript 函数中的参数?

在下面的方法调用registerDevice中,我想在该函数范围之外获取匿名函数的“状态”值。

pushNotification.registerDevice({alert:true, badge:true, sound:true}, function(status) {
  // if successful status is an object that looks like this:
  // {"type":"7","pushBadge":"1","pushSound":"1","enabled":"1","deviceToken":"blablahblah","pushAlert":"1"}
  console.warn('registerDevice:%o', status);    
});

【问题讨论】:

  • 您可以将其从该范围传递到任何其他函数,就像您对console.warn 所做的那样。但是,它似乎是一个异步回调;所以 setting 将它设置为外部范围内的任何变量都没有多大意义。不,从匿名函数返回的值可能只能由pushNotification.registerDevice确定,它会调用它。
  • @Bergi 我怀疑有问题的函数是异步调用的
  • @Alnitak:是的,我也是。我是否另有说明?很抱歉进行了许多编辑:-)
  • @Bergi 在我回复的第一个版本的评论中没有说明。

标签: javascript node.js


【解决方案1】:

假设提供的函数是异步调用的,您不应该在该范围之外使用它的返回值,因为您不知道该函数将在什么时候被调用。

您需要从该回调函数中开始所有进一步的处理,其中status 变量要么在范围内,要么直接传递给后面的函数,即

pushNotification.registerDevice({alert:true, badge:true, sound:true}, function(status) {
    console.warn('registerDevice:%o', status);

    // do stuff with "status"
    func1(status);

    // even put it in a global if you really must
    global.status = status;
});

// processing continues here immediately, you can't access
// "status" here because it won't have been set yet.

console.log(global.status);  //  -- probably undefined

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2016-03-01
    相关资源
    最近更新 更多