-1

I have some problem with understanding promises. Could you help me please:

I'm trying to use node-geocoder library.

So, this is a function, which should return an array of latitude and longitude of some point on the Google map.

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
}

Previous code should be ok for this test:

import getLocation from './index'

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

Test is failing and I'm receiving the following error message:

Expected value to equal:
  [48.8698679, 2.3072976]
Received:
  {"fulfillmentValue": undefined, "isFulfilled": false, "isRejected": false, "rejectionReason": undefined}
Entry Guy
  • 425
  • 1
  • 7
  • 18
  • how to open a package that has not been delivered yet? A Promise is like a shipping confirmation, just a placeholder for the stuff you're awaiting. All you can do with that thing, is waiting for the promise to get fulfilled/the package to be delivered. `.then()` you can do whatever you want, with whatever you got. – Thomas Jun 26 '17 at 17:43

1 Answers1

-1

Promises... ARE THE BEST!

For me, it was hard to grasp, once I got it, I got it.

Read the comments, I used them to describe the promise, not the code in the promise.

Here is a solid example.

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);
}
Christian4423
  • 1,746
  • 2
  • 15
  • 25