简体   繁体   English

异步/等待不等待 javascript 中的返回值

[英]async/await not waiting for return value in javascript

I am currently trying out Next.js and Prisma, but had difficulties on getting values from a database.我目前正在试用 Next.js 和 Prisma,但很难从数据库中获取值。 The values are set to undefined despite having await in it.尽管其中有await ,但这些值仍设置为undefined

My index.js:我的索引.js:

import * as Database from "../../../Database";

export async function getServerSideProps() {
    const username = await Database.getUsername('633d5c12e0bf4ed28b2c3428') //Undefined
    return {        
        props: {
            username: username
        }
    };
}

My Database.js我的数据库.js

const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient();

export async function getUsername(userid) {
    const query = await prisma.user.findMany({
        where: {
            id: userid
        },
        select: {
            username: true,
        }
    })
    return query[0].username; //Debugging confirms query[0].username has the correct value
}

I put breakpoint on both when I assign const username = await... and return query[0].username;当我分配const username = await...return query[0].username; and it was seen that it first stop at const username = await... and then stopping at return query[0].username .可以看到它首先停在const username = await...然后停在return query[0].username I can confirm Database.getUsername(userid) is working as indended and returns the correct value but getServerSideProps() is not waiting for Database.getUsername(userid) before assigning username to undefined我可以确认Database.getUsername(userid)正在按预期工作并返回正确的值,但getServerSideProps() ) 在将用户名分配给 undefined 之前不等待Database.getUsername(userid)

You're not returning from the getStaticProps() so NextJS has no idea what props there are你没有从 getStaticProps() 返回所以 NextJS 不知道有什么道具

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

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