Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting Promise instead of a value?

I think I do not understand, why am I getting Promise in return? I need to create object. Both options to return a value from promise do not work.

Why is it so? What am I missing?

Solution: create variable inside t().then(res=>{const myVar = {...}})

// a.js
exports.t = (key, lang, props) => {
    return i18next.changeLanguage(lang).then(t => {
        return t(key, props);
    });
};

// b.js
import {t} from './a.js'
const myVar = {
  a: "a",
  b: "b",
  c: (()=>{
     switch (template) {
       case 'a':
         // Promise should return value here from t();
       default:
         break; 
     }
  })(),
  d: (async () => {
     switch (template) {
       case 'a':
         // Not working, returns Promise... Why?
         return await t('email.Registration Confirmation', lng);
       default:
         break; 
     }
  })(),
  e: (()=>{
     switch (template) {
       case 'a':
         // Not working, returns Promise... Why?
         return t('email.Registration Confirmation', lng).then(res => {
           return res;
         });
       default:
         break; 
     }
  })()
}

Is it possible at all, that JavaScript waits for that Promise to be resolved, and then finishes creating an object?

like image 333
ezik Avatar asked Jul 01 '19 16:07

ezik


People also ask

Why my function is returning a promise?

Every async function returns a promise, so if the function is async, we immediately conclude that it returns a promise. Our second condition checks if the passed in value is a function and invokes it, passing the result to the isPromise() function.

Can a promise return a value?

It's really important to note that the Promise object doesn't return a value, it resolves a value via the then() method. It is the fetch() function that returns a value, which is a Promise instance.

What is value of promise?

The value promise is a process that identifies why you are in business, why your ideal clients remain loyal to your business, and why your customers and vendors continue to conduct business with you.


1 Answers

async and await are tools to manage promises by letting you use syntax that appears to be non-asynchronous inside an async function.

Consequently, an async function will always return a promise (which will resolve to whatever the return value is when all the promises inside it have resolved).


You are wrong about the function after case 'Register':. It returns a promise. You have no code to examine what it returns though.

like image 132
Quentin Avatar answered Oct 31 '22 16:10

Quentin