简体   繁体   English

在NodeJS模块中导出变量之前,我可以等待承诺解决(HTTP请求)吗?

[英]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: 如果我编写一个模块来发出HTTP请求并计算值,则当我需要/导入时,它将返回一个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? 我可以设计异步模块来等待HTTP响应并返回值而不是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. 另外,当您将getCurrencyConversion分配给myComputedValue时 ,实际上分配了未完成的promise,因为当您定义诸如myComputedValue之类的变量时,它将立即分配,因此Javascript将不会等待。 That why javascript fast 那就是为什么JavaScript快速

you can make your code async using Promises you shuld just wrap it into promise 您可以使用Promises使代码异步,只需将其包装成Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/zh-CN/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. 有关更多信息,请访问https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await,如果有保证,它将返回该值本身,否则将返回该值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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