eran eran - 1 year ago 68
Javascript Question

How to get err and result when using away

I have a function that receives a callback as a parameter. For example:

client.sendMessage(params, (status, response) => {
console.log('Status: ', status);
console.log('API Response:\n', response);

I then promisify it:

const Promise = require('bluebird');
const sendMessageFunc: Object = Promise.promisify(client.sendMessage);

Then I call it:

result = await sendMessageFunc(params);

I actually want to get the
(status, response)
to then do:

(status, response) = await sendMessageFunc(params);
console.log('Status: ', status);
console.log('API Response:\n', response);

But that is not valid syntax. What should I do? What is the "result" object that is being returned to me?

Answer Source

The whole point of await is to flatten you asynchronous code to be like a synchronous code which would throw in a case of error (like JSON.parse for example)
when awaiting on an asynchronous function - if the asynchronous function returned a result - it is returned as if the function was synchronous,
if the asynchronous function threw an exception - await re-throws it, as if the function was synchronous.

so, first of all, there is no "status", only exceptions. you should surround your await expression with try/catch:

    let response = await sendMessageFunc(params);
    console.log('API Response:\n', response);
    console.error('an error was thrown: ' + e.toString());

the promise is just a convenient vehicle to implement a coroutine (which is what async/await keywords actually create). don't think in terms of promises when using await, it's just an implementation detail.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download