Home > database >  Return a callback in node.js
Return a callback in node.js

Time:07-01

My uploadPhoto function should return the id (int) of the photo that has been uploaded.

so inside my main function I've got let photoId = await uploadPhoto(image, name);

here's the code of the uploadPhoto function: First attempt

async function uploadPhoto(image, name) {
    try {

        let file = fs.readFileSync( image );

        await client.uploadFile({
                    name: image,
                    type: "image/jpg",
                    bits: file
                }, function( error, data ) {
                    return data.id
                });

    } catch (err) {
        console.log(err);
    }
}

Second attempt

async function uploadPhoto(image, name) {
    try {

        let file = fs.readFileSync( image );

        function uploadF (callback){
             client.uploadFile(  { name: image, type: "image/jpg", bits: file } , function( error, data ) {
                return callback(data.attachment_id);
            });
        }

        let res = await uploadF(function (data){
           return data;
        });

    } catch (err) {
        console.log(err);
    }
}

CodePudding user response:

Your uploadFile function doesn't return a Promise. That means that putting await in front won't make it wait until it's done. But you can wrap the function with a little bit of code so a Promise is returned.

// Call "resolve()" when the asynchronous action is done
// call "reject()" when an error occurs.
const data = await new Promise((resolve, reject) => {
  client.uploadFile({
    name: image,
    type: "image/jpg",
    bits: file
  }, function( error, data ) {
    if (error) {
      reject(error);
      return;
    }
    resolve(data.id);
  });
});
console.log(data.id);

Alternatively to wrapping it yourself, there is a helper function to do it for you:

const { promisify } = require('util');

// ...

// The .bind() might not be needed or it might be.
// Hard to tell without knowing what library you're using.
const upload = promisify(client.uploadFile).bind(client);

// ...

const data = await upload({
  name: image,
  type: "image/jpg",
  bits: file
});
console.log(data.id);
  • Related