我可以“解开”Axios给出的这个承诺,而不必使用async / await吗?

时间:2018-04-11 00:16:38

标签: javascript promise axios

我称之为此功能:

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()将解开承诺。没有async / await这可能吗?

2 个答案:

答案 0 :(得分:1)

您不需要使用async / await。你可以这样做你想做的事情:

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
        });
    });

});

答案 1 :(得分:0)

假设您有一系列查询,那么您可以使用Promise.all作为jfriend声明:

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
      })
  );
});

Async await语法如下所示:

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捕获错误并解析为未定义)。