簡體   English   中英

在NodeJS模塊中導出變量之前,我可以等待承諾解決(HTTP請求)嗎?

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

我需要在無法進行異步處理的同步腳本中使用異步計算的值

如果我編寫一個模塊來發出HTTP請求並計算值,則當我需要/導入時,它將返回一個Promise:

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

我可以設計異步模塊來等待HTTP響應並返回值而不是Promise嗎? 我是不是該?

我希望能夠:

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

在我的小腳本中,阻塞不會打擾我,在繼續之前等待請求是有意義的。

但我想更好地了解如何處理此類情況。 我目前的理解是,一旦異步,您將永遠無法“返回”。 同步腳本需要支持異步,否則將無法正常工作。

承諾回報承諾不是價值

另外,當您將getCurrencyConversion分配給myComputedValue時 ,實際上分配了未完成的promise,因為當您定義諸如myComputedValue之類的變量時,它將立即分配,因此Javascript將不會等待。 那就是為什么JavaScript快速

您可以使用Promises使代碼異步,只需將其包裝成Promise

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function

您可以創建一個異步函數並獲取值,然后再繼續下一步。 有關更多信息,請訪問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