簡體   English   中英

我可以在不使用async / await的情況下“解開” Axios的承諾嗎?

[英]Can I “unwrap” this promise given by Axios without having to use async/await?

我稱這個功能為:

let bing_web_search = function(search) {
    let searchEncoded = encodeURIComponent(search);
    return axios.get(
        'https://api.cognitive.microsoft.com/bing/v7.0/search?q=' + searchEncoded + '+site:https://docs.microsoft.com/en-us/azure/&mkt=en-us', {
            headers: { 'Ocp-Apim-Subscription-Key' : process.env.BING_SUBSCRIPTION_KEY }
        })
    .then(function(response) {
        return response.data.webPages;
    })
    .catch(function(error) {
        console.log(error)
    });
}

...在我的控制器中的此功能內

router.get('/search/results', async function(req, res) {
    let searchResults = bing.bing_web_search(req.query.search_query);
    let test = await searchResults.then(function(results) {
        return results
    });

    res.render('../views/results', {
        test : test
    });
})

我沒有看到必須在Axios文檔中使用async / await,沒有它們,我將無法使用它。 我一直Promise { pending} ,因此為什么我兩次使用then()認為第二個then()會破壞承諾。 沒有異步/等待,這可能嗎?

您不需要使用異步/等待。 您可以這樣操作:

router.get('/search/results', function(req, res) {
    const searchResults = bing.bing_web_search(req.query.search_query);

    searchResults.then(function(results) {
        res.render('../views/results', {
            test : results
        });
    });

});

假設您有一系列查詢,則可以按照jfriend所述使用Promise.all

router.get('/search/results', function(req, res) {
  Promise.all(
    req.query.search_queries.map(//assuming you have an array of queries
      query=>bing.bing_web_search(query)
    )
  ).then(
    results=>
      res.render('../views/results', {
        test : results
      })
  );
});

異步等待語法將如下所示:

router.get('/search/results', async function(req, res) {
  const results = await Promise.all(
    req.query.search_queries.map(//assuming you have an array of queries
      query=>bing.bing_web_search(query)
    )
  );
  res.render('../views/results', {
    test : results
  })
});

請注意,兩者都不會捕獲任何錯誤(您的bing_web_search捕獲錯誤並解析為未定義)。

暫無
暫無

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

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