【问题标题】:How do I use aysnc/await in this superagent call?如何在这个 superagent 调用中使用 async/await?
【发布时间】:2020-09-23 00:36:37
【问题描述】:

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

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】:

我重新制定了我的答案。我想我之前的理解有误。您可以将整个序列包装到一个 Promise-returning 函数中,该函数在响应回调后解析:

    function callSuperagent() {
        return new Promise((resolve, reject) => {
            return request
                .post(my api call)
                .send(params) // an object of parameters that is to be sent to api
                .end((err, res) => {
                    if(!err) {
                        console.log('get response', res);
                        // uncomment this to see the catch block work
                        // reject('Bonus error.');
                        resolve(res);
                    } else {
                        console.log('error present', err);
                        reject(err);
                    }
                });
        });
    }

然后,您可以创建一个异步函数并等待它:

    async function doSomething() {
        try {
            const res = await callSuperagent();

            // uncomment this to see the catch block work
            // throw 'Artificial error.';

            console.log('res', res);

            console.log('and our friend:', res.resImpVariable);
        } catch (error) {
            throw new Error(`Problem doing something: ${error}.`);
        }
    }

    doSomething();

或者如果你不做doSomething,会是这样的:

callSuperagent()
    .then((res) => {
        console.log('res', res);
        console.log('and our friend:', res.resImpVariable);
    })
    .catch((err) => {
        console.log('err', err);
    })

【讨论】:

  • 谢谢,我在哪里添加 doSomething 方法?解决后立即?
  • 一切都包含在里面。您将使用两个函数定义(可以在该文件中的任何位置)替换您现在拥有的所有内容,并且只需调用一次doSomething()。我很难改进我所说的,因为我看不到request.post().send().end()之前和之后发生了什么@
猜你喜欢
  • 2018-12-28
  • 2019-07-01
  • 2017-10-24
  • 2011-05-04
  • 2018-03-27
  • 2019-12-04
  • 2015-04-06
  • 2017-11-15
  • 2022-11-18
相关资源
最近更新 更多