【问题标题】:how to use async await with https post request如何将异步等待与 https 发布请求一起使用
【发布时间】:2019-03-27 19:29:32
【问题描述】:

我正在寻找将 async / await 与 https post 一起使用的方法。请帮帮我。我在下面发布了我的 https 邮政编码 sn-p。我该如何使用异步等待。

const https = require('https')

const data = JSON.stringify({
  todo: 'Buy the milk'
})

const options = {
  hostname: 'flaviocopes.com',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', (d) => {
    process.stdout.write(d)
  })
})

req.on('error', (error) => {
  console.error(error)
})

req.write(data)
req.end()

【问题讨论】:

    标签: node.js https request node-modules


    【解决方案1】:

    基本上,您可以编写一个返回Promise 的函数,然后您可以将async/await 与该函数一起使用。请看下面:

    const https = require('https')
    
    const data = JSON.stringify({
      todo: 'Buy the milk'
    });
    
    const options = {
      hostname: 'flaviocopes.com',
      port: 443,
      path: '/todos',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
      },
    };
    
    async function doSomethingUseful() {
      // return the response
      return await doRequest(options, data);
    }
    
    
    /**
     * Do a request with options provided.
     *
     * @param {Object} options
     * @param {Object} data
     * @return {Promise} a promise of request
     */
    function doRequest(options, data) {
      return new Promise((resolve, reject) => {
        const req = https.request(options, (res) => {
          res.setEncoding('utf8');
          let responseBody = '';
    
          res.on('data', (chunk) => {
            responseBody += chunk;
          });
    
          res.on('end', () => {
            resolve(JSON.parse(responseBody));
          });
        });
    
        req.on('error', (err) => {
          reject(err);
        });
    
        req.write(data)
        req.end();
      });
    }
    

    【讨论】:

    • 好方法!拯救了我的一天!
    • 我在想,如果你把doRequest函数声明为async,那不就等于把代码封装在一个promise里面了吗?
    【解决方案2】:

    我也遇到了这个问题,找到了这篇文章,并使用了 Rishikesh Darandale (here) 的解决方案。

    await 文档指出 await 运算符用于等待 Promise。不需要从函数返回承诺。你可以只创建一个 Promise 并在其上调用 await。

    async function doPostToDoItem(myItem) {
    
        const https = require('https')
    
        const data = JSON.stringify({
            todo: myItem
        });
    
        const options = {
            hostname: 'flaviocopes.com',
            port: 443,
            path: '/todos',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': data.length
            },
        };
    
        let p = new Promise((resolve, reject) => {
            const req = https.request(options, (res) => {
                res.setEncoding('utf8');
                let responseBody = '';
    
                res.on('data', (chunk) => {
                    responseBody += chunk;
                });
    
                res.on('end', () => {
                    resolve(JSON.parse(responseBody));
                });
            });
    
            req.on('error', (err) => {
                reject(err);
            });
    
            req.write(data)
            req.end();
        });
    
        return await p;
    }
    

    【讨论】:

      【解决方案3】:

      您只能将 async-await 与 Promises 一起使用,并且 Node 的核心 https 模块没有内置 promise 支持。所以你首先要把它转换成 promise 格式,然后你就可以使用 async-await 了。

      https://www.npmjs.com/package/request-promise

      此模块已将核心 http 模块转换为 promisified 版本。你可以用这个。

      【讨论】:

      • request-promise 已被弃用,因为它扩展了现已弃用的请求包,请参阅github.com/request/request/issues/3142
      • -1,另外,如果你拉入一个 npm 包来使用它,那么使用标准 https 包有什么意义?使用https 的全部意义在于不添加臃肿的依赖项。
      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多