Here is simple scenario..
I want to convert these code given in firebase documentation to my api..
How can I convert it to callback function?
var uid = "some-uid";
admin.auth().createCustomToken(uid)
.then(function(customToken) {
// Send token back to client
})
.catch(function(error) {
console.log("Error creating custom token:", error);
});
Here is the link of documentation..
https://firebase.google.com/docs/auth/admin/create-custom-tokens
The promise constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject. Like throw in plain old JavaScript, it's customary, but not required, to reject with an Error object.
For example, a function to read a file may start reading file and return the control to the execution environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as a parameter.
A callback function is passed as an argument to another function whereas Promise is something that is achieved or completed in the future. In JavaScript, a promise is an object and we use the promise constructor to initialize a promise.
Callbacks are functions passed as arguments into other functions to make sure mandatory variables are available within the callback-function's scope. Promises are placeholder objects for data that's available in the future.
If you want to use node-style callbacks on a promise, invoke them like this:
.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
Some promise libraries also have helper functions for that, like Bluebirds .asCallback(callback)
.
In NodeJS > 8.2 you have a require('util').callbackify()
(opposite of require('util').promisify()
):
const { callbackify } = require('util');
callbackify(() => admin.auth().createCustomToken(uid))((err, customToken) => {
// ...
});
Or if you have a callback from somewhere else:
const { callbackify } = require('util');
callbackify(() => promise)(callback);
Note that it receives a function that returns a promise and not the promise itself, and it returns a function that receives a callback and does not receive a callback itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With