Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert promise into callback in node js?

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 
like image 342
Vishant dhandha Avatar asked Nov 16 '16 19:11

Vishant dhandha


People also ask

How do you put a promise in callback?

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.

How do you callback in node JS?

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.

Is callback and promise same?

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.

What is the difference between callback and promise in Nodejs?

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.


2 Answers

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).

like image 106
Bergi Avatar answered Oct 29 '22 17:10

Bergi


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.

like image 34
Oded Niv Avatar answered Oct 29 '22 18:10

Oded Niv