简体   繁体   中英

Can I await promise resolution (HTTP request) before exporting a variable in NodeJS module?

I need to use an asynchronously computed value in a synchronous script which I cannot make async.

If I write a module to make the HTTP request and calculate the value, when I require / import it will return a Promise:

// sync-script.js
const getCurrencyConversion = require('./get-currency-conversion')
getCurrencyConversion().then(result => console.log('Well too late now'))

Can I design my async module to await the HTTP response and return a value instead of a Promise? Should I?

I'm looking to be able to:

// sync-script.js
const getCurrencyConversion = require('./get-currency-conversion')
const myComputedValue = getCurrencyConversion(42)
// do sync stuff with it from here on out

Blocking wouldn't bother me in my little script, it makes sense to wait for the request before proceeding.

But I would like to better understand how to deal with situations like these. My current understanding is once you go async you can never "go back". The sync script needs to support async or it won't work.

Promises return Promise not a Value

Also, When you assigned getCurrencyConversion to myComputedValue you actually assigned the promise which is pending because when you define a variable like myComputedValue it will assign immediately so Javascript will not wait. That why javascript fast

you can make your code async using Promises you shuld just wrap it into promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

You can create a async function and get the values before proceeding to the next step. For more info go through this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await if it's a promise it will return that otherwise the value itself.

 const getCurrencyConversion = require('./get-currency-conversion') const myComputedValue = async()=> await getCurrencyConversion(42); console.log('value is',myComputedValue) 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM