【问题标题】:Using async-await not returning the values使用 async-await 不返回值
【发布时间】:2020-09-21 18:33:16
【问题描述】:

我使用以下有效的代码!我能够获取传播中的数据(然后),http200

Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

现在我想用 async function 包装它,它返回两个响应(responses[0],responses[1])

我已经创建了这个函数

const FetchData = async (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

// add this return 
return {
    run: aToken ,
    app: bToken
};

)}

现在我创建了函数来调用它并获取令牌

async function main() {

    let val = await FetchData();
    console.log(val)


}

问题是我在val 属性中得到了空值,而在主函数中放置了一个断点 我看到我进入了控制台,然后才真正从 ).then(axios.spread(( 获取值, 知道如何采用代码从扩展运算符返回值然后调用控制台吗?

【问题讨论】:

标签: javascript node.js typescript promise async-await


【解决方案1】:
const res = await Promist.all([...])
return { run: res[0], app: res[1] }

【讨论】:

    【解决方案2】:

    您没有正确使用async-await。您需要等待Promise.all。一旦两个承诺都得到解决,响应数据将位于您从axios 获得的每个响应对象内名为data 的属性中。如果你需要整个响应对象,那么你可以解构它

    这是一个例子

    const FetchData = async (): Promise<{ run: string; app: string }> => {
        try {
            const [response1, response2] = await Promise.all([
                axios({
                   ...
                }),
                axios({
                   ...
                })
            ]);
    
            return {
              run: response1,
              app: response2
            };
    
       } catch (error) {
          console.log(error);
       }
    };
    

    这是一个demo,它从jsonplaceholder api 的两个端点获取数据

    【讨论】:

    • 谢谢,我现在就试试。 then 呢,我没看到?
    • then里面我正在获取数据,你能把它添加到例子中吗?
    • 使用async-await 时不需要then 块。请参阅我在答案中包含的 jsonplaceholder api 的演示。它从 2 个端点获取数据
    【解决方案3】:

    你需要改变你的return语句的位置:

    更新的代码有变化:

    const FetchData = (): Promise<{ run: string; app: string }> => {
    
    let aToken:string;
    let bToken:string;
    // Return the promise here
    
    return Promise.all([
        axios({
          method: 'post',
          url: 'https://oauth2.-arch.mand.com/oauth2/token',
          data: qs.stringify({
            'grant_type': 'client_credentials'
          }, {
            'scope': 'run:crud'
          }),
          headers: {
            'Accept': 'application/json',
            'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
            'Content-Type': 'application/x-www-form-urlencoded',
          }
        }),
        axios({
          method: 'post',
          url: 'https://oauth2.-arch.mand.com/oauth2/token',
          data: qs.stringify({
            'grant_type': 'client_credentials'
          }, {
            'scope': 'exe:crud'
          }),
          headers: {
            'Accept': 'application/json',
            'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
            'Content-Type': 'application/x-www-form-urlencoded',
          }
        })
      ]).then(axios.spread((...responses: AxiosResponse[]) => {
          aToken = responses[0];
          bToken = responses[1];
    
          // This return is for getting the data once the promise is resolved either with then or await
          return {
             run: aToken ,
             app: bToken
          };
        }).catch(function(error: any) {
           console.log("Error: " + error);
           return error;
        });
    
    )}
    

    由于您在解决承诺之前返回值,因此您不会获得任何数据。 您需要返回承诺,然后您需要返回所需的数据,以便在调用函数中解决承诺后获取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2019-04-22
      • 2020-10-02
      • 2019-03-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      相关资源
      最近更新 更多