-1

How I can return value from callback function?

The code

function storeData(data) {
  const id = "5f354b7470e79f7e5b6feb25";

  const body = { name: "john doe" };

  bucket.insert(id, body, (error, result) => {
    console.log(error, result); // i want to return error & result from this callback
  });
}

export default {
  async createAd(_, { data }, { request }) {
    try {
      const dataa = await storeData(data);

      return; // to here
    } catch (error) {
      console.log(error);
    }
  },
};

Here I need to return the value(error, result) comes from bucket.insert callback to function createAd and return that value from there.

 bucket.insert --> createAd 

How should it actually work

  • when createAd function invokes
  • createAd function should call storeData(data) function where data stores in DB
  • after storing the data with function bucket.insert
  • bucket.insert callback return the value error and result
  • storeData should return the bucket.insert callback values to createAd
  • createAd return value should contians the storeData return value

bucket.insert should contain a callback else it throws an error Third argument needs to be an object or callback.

solution tried

  • promisifing bucket.insert with nodejs util.promisify
U.A
  • 2,991
  • 3
  • 24
  • 36
  • 1
    Brute force conversion to promise: `return new Promise((res, rej) => bucket.insert(..., (error, result) => { if (error) rej(error) else res(result); }))`… – deceze Aug 13 '20 at 15:22

1 Answers1

2

You could create a custom "Promisify".

E.g:

function storeData(data) {
  return new Promise((resolve, reject) => {
    const id = "5f354b7470e79f7e5b6feb25";

    const body = { name: "john doe" };

    bucket.insert(id, body, (error, result) => {
      if (error) reject(error)
      
      resolve(result)
    });
  })
}