Say I have the following function:
const someFunc = async(obj) => {
const { x, y } = obj;
const result = await devices.update(
{ x: x, y: y },
{ $set: { z: 1 } },
{ upsert: false }
);
if (result.nModified !== 1) throw new Error("Some error");
return result;
};
And I call it like this:
try {
await someFunc();
catch (err) {
console.log(err);
}
I can't return device.update(...)
since I need to perform the test for the number of documents modified inside the function. I also know that someFunc()
wraps the returned result in a Promise
object, but was not sure if this code is considered a clean code.
Your code looks valid. If you skip await
then it won't wait until it resolves the Promise
inside. Instead it is considering the return value as a resolved Promise
. From the documentation for await
:
If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
So I made a quick example just to see the difference without and with await
keyword.
Please consider the following code.
(async () => { console.log('async function started'); const runAsync = async (value) => { const result = await new Promise(resolve => { setTimeout(() => resolve(value), 2000); }); return result; }; const dataWithoutAwait = runAsync('value'); console.log('data without await', dataWithoutAwait); const dataAwait = await runAsync('value'); console.log('data with await', dataAwait); })();
I hope this clarifies and help your question.
I see nothing wrong in this. Look perfectly valid.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.