eran eran - 5 days ago 5
Javascript Question

How to get err and result when using await

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

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:

try{
    let response = await sendMessageFunc(params);
    console.log('API Response:\n', response);
}
catch(e){
    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.

Comments