Trouble with custom callback function

Trouble with custom callback function
0.0 0

#1

I’m trying to write a function that will return a value from an asynchronous call through a callback function:

function showBar(callback) {
let value;
AsyncStorage("key", (err, result) => {
result ? value = true : value = false;
callback(value)
}
}

But if i do showBar((bool) => {}) it says that callback is not a function. I have no idea why it’s saying that.


#2

(bool) => {}

I don’t recognise this as a function definition in any form of JS.

callback(value)

Where is this function defined?


#3

That looks like it should work. I tried to reproduce it here, but I don’t get an error. Perhaps the error is referring to a callback somewhere else?

It’s an arrow function expression, which is new in ES6.


#4

In your demo code you don’t declare callback anywhere. What’s happening here?


#5

callback is the argument passed to showBar()


#6

I got the callback to work! I never really implemented my own callback before so I had to read the documentation. I’m still not 100 percent sure why it works, but adding another parameter to the function worked:

let value;
function showBar(val, callback) {
  AsyncStorage("key", (err, result) => {
    result ? val = true : val = false;
    callback(val);
  }
}
showBar(value, (bool) => {return bool});

It now recognized callback as a function


#7

Ok now the function definition’s signature matches the function call. :thumbsup:
Makes sense to me now.


#8

Both pieces of code have a missing closing parenthesis for the AsyncStorage call:

...
callback(val)
})
...

Other than that I don’t see a syntax or reference problem with showBar((bool)=>{}) - in fact with a single parameter you don’t even need the parentheses showBar(bool=>{})