【问题标题】:How do I use RequestPromise in TypeScript?如何在 TypeScript 中使用 RequestPromise?
【发布时间】:2017-03-14 08:59:01
【问题描述】:

我已安装 request-promise 库并尝试在我的 TypeScript 应用程序中使用它,但运气不佳。

如果我这样使用它:

import {RequestPromise} from'request-promise';

RequestPromise('http://www.google.com')
        .then(function (htmlString) {
            // Process html...
        })
        .catch(function (err) {
            // Crawling failed...
        });

我在 TS 编译输出中看到了这个:

error TS2304: Cannot find name 'RequestPromise'.

如果我这样使用:

import * as rp from'request-promise';

rp('http://www.google.com')
    .then(function (htmlString) {
        // Process html...
    })
    .catch(function (err) {
        // Crawling failed...
    });

我看到一个错误,指出对象 rp 上没有 '.then()' 方法。

如何正确使用 TypeScript?

【问题讨论】:

  • 您是否尝试过import rp from 'request-promise';,然后像上面一样使用rp
  • 现在它可以编译了,但我现在在运行应用程序并调用该代码时看到TypeError: Uncaught error: request_promise_1.default is not a function
  • 我试过import rp = require('request-promise'),它修复了错误。谢谢!
  • 直到我读到this answer,我才明白为什么会这样。 TL;DR - import * as 创建一个模块对象,它不像函数那样“可调用”。

标签: javascript typescript


【解决方案1】:

您必须导入所有 (*) 而不仅仅是 RequestPromise

import * as request from "request-promise";
request.get(...);

This answer详细阐述import/fromrequire的区别。

【讨论】:

    【解决方案2】:

    我就是这样使用request-promise的

    import * as requestPromise from 'request-promise';
    
    const options = {
        uri: _url,
        proxy: https://example.host.com:0000,
        headers: {
            Authorization: 'Bearer ' + token
        }
    };
    
    requestPromise.get(options, (error, response) => {
        if (error) {
            // Do error handling stuff
        } else {
            if (response.statusCode !== 200) {
                 // Do error handling stuff
            } else {
                 // Do success stuff here
            }
        }
    });
    

    【讨论】:

    • 你为什么不把它作为一个承诺(.then(...)),而是作为一个回调?
    【解决方案3】:

    request-promise 有一个 typescript 包

    npm i --save-dev @types/request-promise
    import { get, put, post } from 'request-promise';
    

    用法

    get(options).then(body => {
    
        console.log(body)
    
    }).catch(e => reject);
    

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 2015-03-25
      • 2020-10-28
      • 2021-05-13
      • 2014-08-04
      • 2014-04-29
      • 2017-04-27
      • 2015-11-10
      • 2020-01-02
      相关资源
      最近更新 更多