简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM