-1

如何获取在另一个 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);    
});
4

1 回答 1

0

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

您需要从该回调函数中开始所有进一步的处理,其中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
于 2013-05-15T11:44:05.703 回答