我该如何在这个 superagent 调用中使用 async/await?

3

这是一个superagent调用,我已经导入了request(即从我的superagent组件类导出)如何在"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');
   }
  });

这个程序使用回调模式运行,因此如果要将其转换为async-await模式,则需要将更改转换为返回Promise的形式。 - Shubham Khatri
当然,我该如何在代码中添加它? - user13651619
https://visionmedia.github.io/superagent/#promise-and-generator-support - palaѕн
1个回答

2

我重新阐述我的答案。我之前的理解是错误的。你可以将整个序列包装成一个返回Promise的函数,并在响应回调后进行解决:

    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 方法?在 resolve 后面立即添加? - user13651619
一切都包含在里面。你将用两个函数定义(可以放在该文件的任何位置)和一个对 doSomething() 的调用替换现有的一切。很难让我改进我的话,因为我看不到 request.post().send().end() 之前和之后的内容。 - agm1984

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接