aherlambang
aherlambang

Reputation: 14418

how to get return value of a non-blocking function with an await on it

Lets say i have the following function:

async function commentMediaId(ig, media_id, commentContent, commentIfAlreadyCommented = false, extraInfo = new Object(), callback) {

    try {
        let alreadyExists = ig.db.get('comments').find({media_id: media_id}).value();
        alreadyExists == undefined ? false : true;
        if(alreadyExists && !commentIfAlreadyCommented) {
            console.log('Already commented'.yellow);
            return "already_commented";
        }

        if(commentIfAlreadyCommented || !alreadyExists){
            await ig.media.comment({
                module_name: 'profile',
                mediaId: media_id,
                text: commentContent,
            });


            return callback('success');
        }
    } catch (e) {
        return callback('not success');
    }

}

then I am calling the following function (i do not want to use await here because it will block):

commentMediaId(object, 'someid', 'some string'); 

how can i seet a callback on commentMediaId such that when it returns i get the value of success or not success ?

I basically wanted to do as follows

commentMediaId(object, 'someid', 'some string', function(result) {
   if (result == 'success')



}); 

but I am getting a bunch of syntax error.. any ideas on how to implement it ?

Upvotes: 0

Views: 200

Answers (2)

David Callanan
David Callanan

Reputation: 5790

When you use an async function, you are working with the Promise interface, which exposes a .then() method. You can pass a callback into this method, and the callback will automatically be invoked for you when a value is returned from the commentMediaId function:

commentMediaId(object, 'someid', 'some string') 
  .then(function (result) {
    console.log(result);
  })
;

Finally, you need not take in a callback parameter in the commentMediaId function. You can omit the callback and simply return the values directly. That is the whole idea of the async/await "syntactic sugar", it makes it feel more like a regular function without the need for callbacks.

E.g. the following:

return callback('success');

...should be changed to the following:

return 'success';

Upvotes: 1

Ethan Lipkind
Ethan Lipkind

Reputation: 1156

it looks like you have some typos - asyn should be async and you also have an extra parenthesis in the last argument to the function commentMediaId(...otherArgs, callback(){} instead of commentMediaId(...otherArgs, callback){}

Upvotes: 0

Related Questions