function incrementUserIdRow(value) { // value -> [ { _id: 'abc123', count: 1 } ]
var res = value[0].count += 1;
console.log('Res is ', res);
return res;
}
Promisified version:
async function incrementUserIdRow(value) { // value -> [ { _id: 'abc123', count: 1 } ]
var promise = await new Promise(function (resolve. reject) {
var res = value[0].count += 1;
console.log('Res is ', res);
(err, res) =>
err ? reject(err) : resolve(res)
});
return promise;
}
Says
'This expression reports expression statement which are not assignments or calls.
Such a statement have no dubious semantics, are normally the results of programmer error.
But how is res being passed back in the promisified version as I have another function that depends on this result asynchronously.
only allowing the results to be accessible only from within the function, then does it not make it less modular? I want to define my function and later pass results of this function to another function in order to chain. Am I right by saying that in this case I cannot chain the res to another external function without making another internal async function?
Promises don’t actually make your code synchronous, they only give that illusion by requiring you to maintain a strict chain of Promises. Async/await makes that chain easy to do, but the moment you want to break out and return to “normal” code with a result, you have to do that in the .then() method. You could use the then method to execute your next (non-Promised) code.
function add(a,b) {
return a + b;
}
const c = add(2, 3); // always completes synchronously
console.log(c); // logs 5.
or asynchronous:
let c;
HTTP.get('http://nowhere.com?add=2,3', (error, result) => {
c = result; // always completes asynchronously
console.log(c); // logs 5 after the following console.log is executed
});
console.log(c); // undefined (execution continues here even though the result hasn't been returned)
So to answer your question. If the function is synchronous you don’t need to do anything. If the function is asynchronous you can do one of two things:
Promisify the function, so it just becomes part of the Promise chain (or series of awaits in an async function).
Start the Promised function inside the callback of the non-Promised function. I suggest this is an anti-pattern.