简体   繁体   English

为什么我得到的是 Promise 而不是值?

[英]Why am I getting Promise instead of a value?

I think I do not understand, why am I getting Promise in return?我想我不明白,为什么我会得到Promise的回报? I need to create object.我需要创建对象。 Both options to return a value from promise do not work.从 promise 返回值的两个选项都不起作用。

Why is it so?为什么会这样? What am I missing?我错过了什么?

Solution: create variable inside t().then(res=>{const myVar = {...}})解决方案:在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?有没有可能,JavaScript 等待Promise被解析,然后完成创建一个对象?

async and await are tools to manage promises by letting you use syntax that appears to be non-asynchronous inside an async function. asyncawait管理promise 的工具,让您可以在async函数中使用看似非异步的语法。

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).因此, async函数将始终返回一个承诺(当它内部的所有承诺都已解析时,它将解析为任何返回值)。


You are wrong about the function after case 'Register': .您对case 'Register':之后的功能有误。 It returns a promise.它返回一个承诺。 You have no code to examine what it returns though.您没有代码来检查它返回的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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