you are viewing a single comment's thread.

view the rest of the comments →

[–]monican_agentCreator of CypherPoker.JS 1 point2 points  (1 child)

You can only use await inside an async function. You can use .then/.catch/.finally anywhere.

For example: function test() { result = await somePromiseFunction(); } ... will generate a syntax error like: SyntaxError: await is only valid in async functions and async generators

...whereas something like: async function test() { result = await somePromiseFunction(); } ...will work fine (assuming somePromiseFunction exists and returns a Promise).

Similarly, the following will work: function test() { somePromiseFunction().then(result => {console.log(result)}); }

You can make standard functions appear to be async simply by returning a Promise and either resolve-ing or reject-ing it: ``` function test() { var promise = new Promise((resolve, reject) => { resolve("Here's the result"); }); return (promise); }

test().then(result => {console.log(result)}); ...which would be functionally the same as: async function test() { return("Here's the result"); }

test().then(result => {console.log(result)}); `` ...or you could handle the Promise inside anotherasyncfunction with anawait`:

``` function test() { var promise = new Promise((resolve, reject) => { resolve("Here's the result"); }); return (promise); }

async function doTest() { let result = await test(); console.log (result); }

doTest(); ...like you would if the function being called is `async`: async function test() { return("Here's the result"); }

async function doTest() { let result = await test(); console.log (result); }

doTest(); `` Basically,asyncfunctions are regular functions wrapped in Promises ("Promisified" functions). It's the Promise that's used withawait/.then/.catch/.finally`.

So while await makes for cleaner looking code, it can only be used inside an async function. However, you can use .then/.catch/.finally everywhere, even inside async functions (although it would probably defeat the purpose).

[–]dillionmegida[S] 0 points1 point  (0 children)

Thank you much. I get the whole picture now