我如何在此超级代理调用中使用aysnc / await?

问题描述 投票:0回答:1

这是一个超级代理调用,我已经导入了请求(即从我的超级代理组件类中导出)如何在其中将async / await用于“ res.resImpVariable”。

request
  .post(my api call)
  .send(params) // an object of parameters that is to be sent to api 
  .end((err, res) => {
  if(!err) {
     let impVariable = res.resImpVariable;
  } else {
    console.log('error present');
   }
  });
javascript reactjs asynchronous mobx superagent
1个回答
0
投票

您的呼叫具有以下形式:request.post().send().end()end是一个输入函数作为其第一个参数的函数。

您可以将该功能升级为异步功能(请注意async的添加):

request
  .post(my api call)
  .send(params) // an object of parameters that is to be sent to api 
  .end(async (err, res) => {});

然后您可以在其中使用await:

request
    .post(my api call)
    .send(params) // an object of parameters that is to be sent to api 
    .end(async (err, res) => {
        const impVariable = await res.resImpVariable();
    });

为了进行正确的错误处理,我建议也使用try / catch块:

request
    .post(my api call)
    .send(params) // an object of parameters that is to be sent to api 
    .end(async (err, res) => {
        try {
            const impVariable = await res.resImpVariable();

            console.log('impVariable', impVariable);
        } catch (error) {
            throw new Error(`Problem with impVariable: ${error}`.);
        }
    });

如果拒绝返回承诺的异步函数,则执行将通过catch块,因此您可以清理或重试,否则将处理错误。您可以研究“如何避免通过异步/等待吞下诺言”以了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.