簡體   English   中英

在沒有異步功能的情況下等待響應?

[英]Await response without Async Function?

是否可以在函數中等待異步函數的響應,而不使整個函數異步,ala await 沒有異步,或類似的東西? 這方面的一個例子:

const axios = require('axios');
const converter = require('number-to-words');
const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});
function dataFetch() {
    //fetches current exchange rate of NOK to USD
    let data = await axios.get('https://api.exchangeratesapi.io/latest?base=NOK');
    //fetches current value of Norwegian Oil fund
    let res = await axios.get('https://www.nbim.no/LiveNavHandler/Current.ashx');
    //extracts value of Norwegian Oil Fund from response data, and converts it to USD in real time.
    let dolla = (res.data.Value.replace(/\s/g, '') * data.data.rates.USD).toFixed(2);
    //Converts Basic number to number with commas, and a dollar sign.
    let val = formatter.format(dolla);
    //Generates word format of number(i.e. one hundred instead of 100)
    let str = converter.toWords(dolla);
    //Generates word format of cents.
    let cents = converter.toWords(dolla.split('.')[1].substring(0, 2));
    //Returns JSON of commaed value and full word string
    return {num: val, word: `${str} dollars and ${cents} cents`};
}
console.log(dataFetch().val);

我想確保dataFetch()返回的值是從 get 請求收到的數據的處理版本,而不是承諾,或者 null 以便console.log()以美元打印出基金的價值, 而不是 undefined, 或 null, 或其他東西。

幾乎可以肯定有一個簡單的解決方案,但我似乎找不到它,而且它已經破壞了我已經工作了一段時間的代碼。

更新:更新以添加問題的上下文。 我為我稍微不清楚的評論道歉。

您正在dataFetch()函數內進行多個異步 (axios) 調用。 這意味着您的函數將在任何這些異步操作完成之前返回,您對此無能為力。 這就是異步操作在 Javascript 中的工作方式。 因此,您無法從函數中返回最終值。 您的函數在最終值已知之前返回。

有三個選項可以返回最終值:

  1. 承諾
  2. 打回來
  3. 事件

選擇其中之一。

在這種情況下,自然契合將是一個承諾。 無論如何,您必須將dataFetch()函數聲明為async函數,以便您在其中調用await將被允許​​。 這意味着它已經自動返回了一個承諾。 然后要從dataFetch()獲取值,您可以在返回的承諾上使用await.then()

dataFetch().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

這就是異步編程在 Javascript 中的工作方式。

利用我收到的答案,這是我使用的代碼:

function bimFetch() {
    axios.get('https://api.exchangeratesapi.io/latest?base=NOK').then(data => {
        axios.get('https://www.nbim.no/LiveNavHandler/Current.ashx').then(res => {
            let dolla = (res.data.Value.replace(/\s/g, '') * data.data.rates.USD).toFixed(2);
            let val = formatter.format(dolla);
            let str = converter.toWords(dolla);
            let cents = converter.toWords(dolla.split('.')[1].substring(0, 2));
            if(dolla.split('.') === '01')
                currentStatus = { num: val, word: `${str} dollars and ${cents} cent` };
            else
                currentStatus = { num: val, word: `${str} dollars and ${cents} cents` };
        });
    });
}

一旦獲取和格式化都完成,它就會將其響應輸出到currentStatus 我設置了一個setTimeout() ,等待大約 5 秒后,它將通過所有連接的 WebSockets 發送帶有更新狀態的消息。

我要感謝@jfriend00 在這個問題上的幫助,因為我在 JS 異步編碼中學到了寶貴的一課。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM