在Express中使用承诺

时间:2019-03-11 07:18:57

标签: javascript node.js express promise

我想要一个应用程序,用户在其中输入地址作为查询字符串,然后以json对象的形式接收该位置的天气。在天气检索部分,我使用诺言获取地址的纬度和经度,然后再获取天气。还提供用于指定语言和单位的选项。

function getWeather(encodedAddress, units, language) {
    let geoKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
    let geocodeURL = `http://www.mapquestapi.com/geocoding/v1/address?key=${geoKey}&location=${encodedAddress}`;

    return axios.get(geocodeURL).then(({data}) => {
        if (((data.results[0].locations[0].geocodeQualityCode.substring(2)).match(/X/g) || []).length > 1) {
            throw new Error('Unable to find that address')
        }
        const locationInfo = data.results[0].locations[0];
        const lat = locationInfo.latLng.lat;
        const lng = locationInfo.latLng.lng;

        console.log('Here\'s the weather for: ', locationInfo.street, locationInfo.adminArea5,
                                locationInfo.adminArea4, locationInfo.adminArea1, 
                                locationInfo.postalCode);
        
        const weatherKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
        
        units = units ? `units=${units}` : 'auto';
        language = language ? `lang=${language}` :  'lang=en';
        
        const weatherURL = `https://api.darksky.net/forecast/${weatherKey}/${lat},${lng}?${units}&${language}`;
        return axios.get(weatherURL);

    }).then(({data}) => {
        const tempInfo = data.currently;
        const temp = tempInfo.temperature;
        const apparentTemp = tempInfo.apparentTemperature;
        const summary = tempInfo.summary;

        console.log(`It's currently ${temp} degrees and feels like ${apparentTemp} degrees. \nThe local summary is: ${summary}.`);

        return data.currently;
        
    }).catch(error => {
        if (error.code === 'ENOTFOUND') {
            throw new Error('Could not connect to MapRequest server');
        } else {
            throw new Error(error.message);
        }
    });
};

在我的app.js中,我有

app.get('/weather', (req, res, next) => {
    if (!req.query.address) {
        return res.send({
            error: 'You must provide an address!'
        })
    }

    forecast.getWeather(req.query.address).then(function(data) {
         res.send(data);
    });
    next();
});

我在浏览器中收到Cannot read property then of undefined错误。我想这是因为发送响应时,承诺尚未解决。 app.get基于快速文档中的内容,因此我认为可能与我的getWeather函数有关。我如何等待承诺解决,然后执行所有操作?

1 个答案:

答案 0 :(得分:-2)

您可以使用demoPromise npm软件包进行承诺。

尝试一下。

#!/bin/bash
timeString="Mar 15 09:27:26"