Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  177] [ 1]  / answers: 1 / hits: 23974  / 6 Years ago, wed, july 25, 2018, 12:00:00

I am trying to do something like this on global scope in nodejs REPL. As per my understanding both the following statements are valid. see docs



let x = await Promise.resolve(2);
let y = await 2;


However, both these statements are throwing an error.



Can somebody explain why?
my node version is v8.9.4


More From » node.js

 Answers
12

Update


When using Node, the file currently must have an .mjs extension to work.


Top level awaits can be used in browser modules. When used the script tag must include the type attribute which must be set to module:


<script src="/script.js" type="module"></script>

const start = Date.now()

console.log('Pre call.')
await delayedCall()
console.log('Duration:', Date.now() - start)

function delayedCall() {
return new Promise(resolve => setTimeout(() => resolve(), 2000))
}


Old Answer


await can only be used within a function that is labeled async, so there are two ways you can approach this.


Note:
There is a proposal in place that may eventually allow the usage of Top level await calls.


The first way is to create a self invoked function like this:




(async function() {
let x = await Promise.resolve(2)
let y = await 2

console.log(x, y)
})()




Or the second way is to use .then()




Promise.resolve(2).then(async data => {
let x = data
let y = await 2

console.log(x, y)
})




[#53881] Monday, July 23, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackelyn

Total Points: 303
Total Questions: 103
Total Answers: 102

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
jackelyn questions
Thu, Apr 8, 21, 00:00, 3 Years ago
Sun, Feb 28, 21, 00:00, 3 Years ago
Mon, May 25, 20, 00:00, 4 Years ago
Thu, Apr 30, 20, 00:00, 4 Years ago
;