用于等待嵌套在另一个await函数中的函数调用的行业标准是什么?

时间:2018-12-26 05:31:55

标签: node.js promise async-await

我在node.js中有一个函数,该函数在继续之前等待HTTP GET请求。在该GET请求的错误处理程序中,我需要调用另一个函数,并等待它。

根据我的直觉,我应该在第二个函数调用之前放置“ await”。但是,node.js不允许这样做。据我了解,这是因为错误处理程序范围不再标记为异步。我可以绕开它,但是它很快就会意大利面

什么是最佳解决方案?

var accessToken = "SAMPLE ACCESS TOKEN";

const stockDataRequest = async (symbol) =>
{
    console.log("Old access token:", accessToken);

    //Request stock data.
    await axios.get(`https://api.tdameritrade.com/v1/marketdata/${symbol}/quotes?authorization=${accessToken}`).then((response) =>
    {
        //unimportant
    })
    .catch((error) =>
    {
        console.log("\n----Axios Request Failed As Planned----\n");

        if(error.response.status == 401)
        {
            accessToken = auth.newAccessToken(); //**WE NEED TO WAIT ON THIS!!!!**
        }
    });

    console.log("New access token:", accessToken, "\n");
}

在身份验证中:

var newAccessToken = () =>
{
    var dataString = 'grant_type=refresh_token&refresh_token=' + refToken + '&access_type=&code=&client_id=GASKETGV2&redirect_uri=';

    request(
    {
        url: 'https://api.tdameritrade.com/v1/oauth2/token',
        method: 'POST',
        headers: headers,
        body: dataString
    }, 
    (error, response, body) =>
    {
        return new Promise((resolve, reject) =>
        {
            if (error || response.statusCode != 200) 
            {
                console.log("rejecting");
                reject("\n\n----New Access Token Request Rejected----\n\n", error);
            }
            else
            {
                console.log("Request for new access token resolved. Now returning from auth.");
                var genToken = "Bearer " + JSON.parse(body).access_token;
                resolve(genToken);
            }
        })

    });

};

这些是结果:

Old access token: SAMPLE ACCESS TOKEN

----Axios Request Failed As Planned----

New access token: undefined

Request for new access token resolved. Now returning from auth.

应该交换最后两个语句,并定义新令牌。

1 个答案:

答案 0 :(得分:2)

我认为您使用async / await缺少了要点,并将其与Promises混合使用。 这就是使用async / await的代码的样子:

var accessToken = "SAMPLE ACCESS TOKEN";

const stockDataRequest = async (symbol) =>
{
  try {
    const response = await axios.get(`https://api.tdameritrade.com/v1/marketdata/${symbol}/quotes?authorization=${accessToken}`);
    // do stuff with response
  } catch (error) {
    if (error.response.status == 401) {
       const newAccessToken = await auth.newAccessToken();
       // do stuff with new accesstoken
    }
  }
}