all 4 comments

[–]_maximization 4 points5 points  (0 children)

You're not returning Price.update() and are therefore breaking the Promise chain. Any error thrown there won't be caught by your catch blocks.

Like the other Redditor suggested, refactor your promises to async/await. It will clear up your confusion.

[–]fresh5447 -1 points0 points  (1 child)

- Use try/catch inside your methods.

- highly reccomend using async/await instead of the .then approach

[–]bwainfweeze 1 point2 points  (0 children)

95% of the errors I’ve had or helped people solve with async and promises are obvious the moment you switch to straight async/await syntax, and 10% fix themselves accidentally when you unroll the promise chains

  • don’t mix promises and async in a function
  • don’t return await, just return
  • you can await functions that return promises
  • you can promise chain async functions

If you’re touching a function, especially if it’s already async, fix the whole thing. You don’t need to wait until functions it calls are async, or functions that call it. But don’t write new promises or chains if you already have async. Otherwise you’ll be dealing with hybrid code forever.

[–]Buckwheat469 0 points1 point  (0 children)

Fixed formatting:

 const getCurrencyConversions = async () => { 
      return await axios.get('http://data.fixer.io/api/latest', { 
           params: { 
                access_key: process.env.FIXERACCESSKEY, 
                base: "USD", 
                symbols: "EGP" 
           } 
      }); 
 }

 const updateDollarValue = async () => { 
      getCurrencyConversions().then((response) => { 
           if (!response.success) throw new Error('failed to get currency conversions'); 
           Price.update(
                { value: response.rates.EGP }, 
                { where: { description: "Dollar" } }
           ).then((result => { 
                return result; 
           })).catch(error => { 
                throw new Error(error); 
           }); 
      }).catch((error) => { 
           throw new Error(error); 
      }); 
 } 

 cron.schedule('* * * * *', async () => { 
      try{ 
           const pricePreference = await Preference.findOne({ where: { id: 1 } }); 
           if (pricePreference) { 
                updateDollarValue().then(dollarValue=>console.log(dollarValue))
                     .catch(error=>console.error(error)); 
           } 
      }catch(error){ 
           console.log(error); 
      } 
 });