为什么在请求的回调中未定义解析?

时间:2017-03-26 15:00:38

标签: node.js

当我在终端中运行下面给出的代码时,我得到以下错误: - ReferenceError:未定义resolve。



const request = require('request');

let geoLocationPromise = (zipCode) => {
return new Promise(()=>{
  request({
    url:`https://maps.google.com/maps/api/geocode/json?address=${zipCode}`,
    JSON: true
  }, (error, response, body)=>{
      if(error){
        reject('Unable to connect to server');
      }else if (response.statusCode === 200) {
        console.log(body);
        resolve(JSON.parse(body.currently, undefined, 2));
      }
  });
});
};

geoLocationPromise(841101).then((loc)=>{
  console.log(loc);
}, (errorMessage)=>{
  console.log(errorMessage);
});




1 个答案:

答案 0 :(得分:1)

您需要为Promise的回调声明参数“reject”和“resolve”,如下所示:

const request = require('request');

let geoLocationPromise = (zipCode) => {
return new Promise((resolve, reject)=>{
  request({
    url:`https://maps.google.com/maps/api/geocode/json?address=${zipCode}`,
    JSON: true
  }, (error, response, body)=>{
      if(error){
        reject('Unable to connect to server');
      }else if (response.statusCode === 200) {
        console.log(body);
        resolve(JSON.parse(body.currently, undefined, 2));
      }
  });
});
};