1

I'm trying to understand Promises as best as I can.

I was wondering if there's a way of returning the data after the promise had been resolved without chaining as much as I have

Basically i was trying to push a new location into the locs array.

loc.service.js :

export const locService = {
  getLocs,
};

const locs = [
  { name: 'Greatplace', lat: 32.047104, lng: 34.832384 },
  { name: 'Neveragain', lat: 32.047201, lng: 34.832581 },
];

function getLocs() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(locs);
    }, 100);
  });
}

map.service.js :

      const place = prompt('Enter place name');
      if (!place) {
        alert('Please enter a valid input');
      } else {
        locService.getLocs().then(locService.setLoc(place, event.latLng));
        locService.getLocs().then((locs) => {
          storageService.save(PLACE_KEY, locs);

thanks a bunch

NewbieAeg
  • 557
  • 3
  • 8
  • 15
  • 2
    Why are you using a promise with an entirely synchronous operation for `getLocs()`? That is just complicating things. In addition, you must pass a function reference to `.then()` and `locService.setLoc(...)` is NOT a function reference. That is executing that function immediately and passing some return value to `.then()`, so it will not wait for the previous promise to finish before executing. There is little here that is correct. But, it looks like mostly make-up code, not real code so we can't really advise more specifically on how to solve the real problem. – jfriend00 Dec 22 '21 at 20:08

1 Answers1

1

Yes. check async/await syntax.

MDN doc


using async/await instead of the .then chain.

      const place = prompt('Enter place name');
      if (!place) {
        alert('Please enter a valid input');
      } else {

       const locs = await locService.getLocs()
       storageService.save(PLACE_KEY, locs);

don't forget to add async on your wrapping function. or add another async function if you don't want to change how it behave.

 funcName = async ()=>{
// the code
}
Tawfik Nasser
  • 1,018
  • 9
  • 17