0

I know similar questions to this have been asked before but I have reviewed them and still am unable to apply to my specific use case. I would greatly appreciate any help that anyone is able to provide.

A bit of background, I have a search tool that users can input a postcode into. Once they click 'Search' the postcode is converted into a Geolocation.

Here is a link to a codepen with the relevant Javascript

const postcodeToBeConverted = "BB80LD";

const conversionTable = {
  BB80LD: [-2.1702448, 53.85482989]
};

// Simplified version of MongoDB query
const postcodeToGeo = new Promise(resolve => {
  return resolve(lookup.BB80LD);
});

// 1.1 Renders incorrectly
// console.log(postcodeToGeo.then(res => res));

// 1.2 Renders correctly
// postcodeToGeo.then(res => console.log(res));

// Injecting value into another object
const masterQuery = {};

// How can inject the Geo value rendered by function 1.2 ?
masterQuery.postcode = postcodeToGeo.then(res => res);

/* 
 * Desired output => 
 *    masterQuery: {
 *        postcode: [-2.1702448,53.85482989]
 *    }
 *
 * Actual output => 
 *    masterQuery: {
 *        postcode: [object Promise]
 *    }
 */

console.log(masterQuery);

My attempts so far:

/* I can't update the value of a variable:
 *
 *   let postcodeholder;
 *   postcodeToGeo.then(res => {postcodeholder = res});
 *   console.log(postcodeholder);
 */  Output => undefined

/* I can't store the return value in a variable:
 *
 *   const postcodeholder = postcodeToGeo.then(res => res);
 *   console.log(postcodeholder);
 */  Output => [object Promise] {}

/* I can't pass the value as part of a function:
 *
 *   const returnObj = async () => {
 *       postcodeToGeo.then(res => {
 *          return {
 *              masterQuery: {
 *              postcode: res
 *              }
 *          };
 *       });
 *   };
 *   returnObj();
 *
 *   Output => Object {
 *    postcode: [object Promise] {}
 *    }

Thank you in advance.

Alex Mckay
  • 3,463
  • 16
  • 27
  • You can't, period. You do your work inside the `then` callback. End of story. – deceze Nov 27 '18 at 16:00
  • Thank you for your response @deceze. I believe I am doing my work within the 'then' callback in the final example I provided, yet I still am not able to return the return value to the object field. I am able to log the return value to the console (covered in the question you linked to) but I am having more trouble assigning the value to an object field. I would appreciate any guidance you would be able to provide. – Alex Mckay Nov 27 '18 at 16:38
  • You’re trying to access the value outside the `then` callback. That simply doesn’t work. The value is not available *at that time.* **Time** is the crux of asynchronous programming. – deceze Nov 27 '18 at 17:14

0 Answers0