0

I have below code

async function callme(){ 
    methods.callfun(x)
             .then(function (res) {
              methods.callfunxx(res)
                     .on("send", function (r) {
                         console.log(r);
                     })
                     .on("error", function (error, r) {
                         console.error(error);
                     });
             });
}

And I want to call like this

const rr = await callme();

but its not waiting to so I am trying to change this in await and tried below

 async function callme(){ 
        const res = await methods.callfun(x);
                const response = await methods.callfunxx(res)
                response.on('send',() => {
                    return (`Successfully`)
                });
                response.on('error',() => {
                    return (`error`)
                });
    }

Till second await its waiting.. but rest is not working as expected... I am trying to return response as per send/error.

Any help

Thanks

Liam
  • 27,717
  • 28
  • 128
  • 190
Md. Parvez Alam
  • 4,326
  • 5
  • 48
  • 108
  • 2
    `methods.callfunxx(res)` probably doesn't return a promise ... and whatever you return in `.on` event handlers goes nowhere and does nothing – Jaromanda X Nov 10 '20 at 04:48
  • `methods.callfunxx(res)` function probably doesn't return a promise. – lala Nov 10 '20 at 04:51

1 Answers1

1

Your current attempt doesn't use promises at all, it just returns a string.

response.on('send', () => {
    return (`Successfully`) // string was returned, but nothing happened afterwards
});

Your function is already async, as denoted by the async in async function. You can already call it like so:

const rr = await callme();

It returns a promise that resolves into undefined.

To make it return a Promise, that resolves/rejects with the values returned by methods.callfunxx, you will need to use the Promise constructor, calling resolve/reject when the event is done, or when an error has occurred.

function callme() {
    const res = await methods.callfun(x);

    const ret_value = methods.callfunxx(res);

    return new Promise(
        (resolve, reject) => {
            ret_value.on("send", resolve).on("error", reject);
        }
    );
};
  • Now, if I'm being honest, I think the question is a duplicate, can someone find the canonical answer to these questions? –  Nov 10 '20 at 05:18
  • Was the canonical I used the one you had in mind? – Bergi Nov 10 '20 at 08:12
  • @Bergi Nothing in particular in mind just would've rather seen this directed to an existing answer. –  Nov 10 '20 at 16:43