你如何将承诺链接起来,但是将类型从一个变为另一个呢?

时间:2016-11-12 04:29:58

标签: javascript angularjs node.js typescript promise

我对nodejs / typescript / promises比较陌生,所以我不确定链接promises的正确方法。

我有一个帮助类,它调用REST api来获取基于ip的地理定位。我对整个回应都不感兴趣,只对城市领域感兴趣。我如何正确地返回一个承诺,当解决时只获得城市字段?

var rest = require("axios");
const ENDPOINT = "http://freegeoip.net/json/";
@Service()
export class GeoIp {
    city(ip: string): Promise<any> {
        let promise: Promise<any>;
        let p = rest.get(ENDPOINT + ip);
        p.then((response) => {
            promise = Promise.resolve(() => {return response.data["city"]});
        }, (error) => {
            promise = Promise.reject(() => { return error});
        });
        return Promise.resolve(p).then((data)=>promise);
    }
}

这是我的测试代码失败,因为收到的数据对象是原始的REST响应对象

import chai = require('chai');
import {GeoIp} from "../../server/services/GeoIp";
var assert = chai.assert;

describe("GeoIp service", () => {
    let geoIp: GeoIp;
    beforeEach("Initialize service", () => {
        geoIp = new GeoIp();
    });

    var IP_VALID = "137.118.222.187";
    it(`Check geolocation of ${IP_VALID}`, (done) => {
        let promise = geoIp.city(IP_VALID);
        promise.then((data) => {
            console.log(data);
            assert.equal(data, "Traphill");
            done();
        });
    });
});

2 个答案:

答案 0 :(得分:3)

var rest = require("axios");
const ENDPOINT = "http://freegeoip.net/json/";
@Service()
export class GeoIp {
    city(ip: string): Promise<any> {
        return rest.get(ENDPOINT + ip).then((res) => res.data.city);
    }
}

答案 1 :(得分:3)

var rest = require("axios");
const ENDPOINT = "http://freegeoip.net/json/";
@Service()
export class GeoIp {
    city(ip: string): Promise<string> {
        return rest
            .get(ENDPOINT + ip)
            .then((response) => response.data.city);
    }
}

then方法始终会返回另一个Promise,并使Promise可以链接。

类似签名看起来也应该是Promise<string>