如何获得承诺的结果?

时间:2017-06-26 16:57:17

标签: javascript ecmascript-6 promise geocoding google-geocoder

我对理解承诺有一些问题。你能帮帮我吗?

我试图使用node-geocoder库。

所以,这是一个函数,它应该在Google地图上返回某个点的纬度和经度数组。

import NodeGeocoder from 'node-geocoder'

export default function getLocation () {
    const geocoder = NodeGeocoder({
        provider: 'google',
    })

    const point = geocoder.geocode('29 champs elysée paris', (error, response) => {
        return [response[0].latitude, response[0].longitude]
    })

    return point
}

以前的代码应该适用于此测试:

import getLocation from './index'

test('This is a test', () => {
    expect(getLocation()).toEqual([48.8698679, 2.3072976])
})

测试失败,我收到以下错误消息:

Expected value to equal:
  [48.8698679, 2.3072976]
Received:
  {"fulfillmentValue": undefined, "isFulfilled": false, "isRejected": false, "rejectionReason": undefined}

1 个答案:

答案 0 :(得分:-1)

承诺......是最好的!

对我来说,很难掌握,一旦拿到它,我就明白了。

阅读评论,我用它们来描述承诺,而不是承诺中的代码。

这是一个很好的例子。

function logIn(email, password) {
  const data = {
    email,
    password
  };

  // first I define my promise in a const
  const AUTH = new Promise((resolve, reject) => {
    // this is a normal Jquery ajax call
    $.ajax({
      url: "/api/authenticate",
      type: "POST",
      data, // es6
      success: function(res) {
        resolve(res); // this will be sent to AUTH.then()
      },
      error: function(err) {
        reject(err); // this will be sent to AUTH.catch()
      }
    })
  });

  // once the resolve callback is sent back, I can chain my steps like this
  AUTH.then((res) => {
      let token = JSON.stringify(res);
      return token;
    })
    .then((token) => {
      var d = new Date();
      d.setTime(d.getTime() + (1 * 24 * 60 * 60 * 1000));
      var expires = "expires=" + d.toUTCString();
      return document.cookie = `token=${token}; ${expires}; path=/`;
    })
    .then(() => {
      return window.location = "/"; // go home
    })
    .catch(errCallback); // skips to this if reject() callback is triggered
}

function errCallback(err) {
  return console.error(err);
}