Problem
Consider:
class GyroJs {
setGyroPosition(pos) {
if (pos === null || typeof pos === 'undefined') {
throw new Error('The position must be defined');
}
this.pos = pos;
}
constructor() {
const gyroscopePosition = NativeModules.MyGyroModule.gyroPosition();
this.setGyroPosition(gyroscopePosition);
}
}
This code will always throw an error because the value of gyroscopePosition
will always be an unresolved Promise
.
It’s important to remember that the bridge that connects JavaScript and native code is asynchronous. We can either receive results from this side by passing in a callback (not done in this example), or by returning a Promise
. In this case, we need to append a then()
call to the gyroPosition()
call and set the position inside it.