为什么我得到承诺而不是价值? [英] Why am I getting Promise instead of a value?

查看:58
本文介绍了为什么我得到承诺而不是价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我不明白,为什么我得到 Promise 作为回报?我需要创建对象.从promise返回值的两个选项都不起作用.

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?

解决方案:在 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; 
     }
  })()
}

JavaScript是否有可能等待该 Promise 解析,然后完成创建对象?

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

推荐答案

async await 是通过允许您使用来管理承诺的工具在 async 函数内部似乎不异步的语法.

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

因此, 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).

您在 case'Register':之后的功能上有误.它返回一个承诺.您没有代码来检查返回的内容.

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

这篇关于为什么我得到承诺而不是价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆