在 Javascript 中将对象 Promise 转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51250211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:28:03  来源:igfitidea点击:

Converting Object Promise to String in Javascript

javascriptreactjssoliditysemantic-ui-reactnext.js

提问by Saensation

I'm working with React, Next.Js, semantic-ui-react and Solidity. It is my goal to print out the users address (from MetaMask) and a ProjectTitle (set by User) as meta infomation for a semantic-ui-react card. To print out the address in the 'header' is working, but I'm not able to print out the ProjectTitle as 'meta'. The Title should be a String but I'm receiving a Object Promise.

我正在使用 React、Next.Js、semantic-ui-react 和 Solidity。我的目标是打印出用户地址(来自 MetaMask)和一个 ProjectTitle(由用户设置)作为语义 ui-react 卡片的元信息。打印出“标题”中的地址是有效的,但我无法将 ProjectTitle 打印为“元”。标题应该是一个字符串,但我收到了一个对象承诺。

static async getInitialProps() {
    const projects = await factory.methods.getDeployedProjects().call();
    return {
        projects
    };
}

async getProjectTitle(address) {
    let title;
    try {
        title = await factory.methods.projectTitle(address).call();
    } catch (err) {
        console.log('err');
    }
    return title;
}

renderProjects() {
    const items = this.props.projects.map(address => {
        return {
            header: address,
            color: 'green',
            description: (
                <Link route={`/projects/${address}`}>
                    <a>View Project</a>
                </Link>
            ),
            **meta: this.getProjectTitle(address)**,
            fluid: true,
            style: { overflowWrap: 'break-word' }
        };
    }, );
    return <Card.Group items={items} />
}

Part of the Solidity Contract:

Solidity 合约的一部分:

address[] public deployedProjects;
mapping(address => string) public projectTitle;

function createProject(string startup, string title, string deadline, string description, uint wage) public {
    address newProject = new Project(startup, title, deadline, description, wage, msg.sender);
    projectTitle[newProject] = title;
    deployedProjects.push(newProject);
}

function getDeployedProjects() public view returns (address[]) {
    return (
        deployedProjects
    );
}

The basic framework is from the Udemy Course "Ethereum and Solidity: The Complete Developer's Guide" by Stephen Grider.

基本框架来自 Stephen Grider 的 Udemy 课程“Ethereum 和 Solidity:完整的开发人员指南”。

回答by Saensation

There is no direct way to convert an Object Promise into a String. The only way to continue processing is to call an awaitfunction or use .then()and a callback function.

没有直接的方法可以将 Object Promise 转换为 String。继续处理的唯一方法是调用await函数或使用.then()和回调函数。