承诺不尊重

发布于 2025-01-26 11:47:36 字数 2173 浏览 2 评论 0原文

我已经对此猛击了一段时间,但我无法弄清楚。

我有Main.js实例化用户对象并从中登录值。

main.js

jsUser = new user();
console.log(jsUser.passTimes);

的数据

i然后有user.js文件,该文件包含该类并获取Passtimes user.js

class user{

    // construct the object
    constructor(obj){

        // just set stuff up, cuz why not?
        this.pTimes = [];

    }

    loadPTimes(){

        // return a promise
        return new Promise((res,rej)=>{

                $.ajax({
                    url: './data/importantfile',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        method: 'getData',
                        termCode: termCode
                    },
                    success: (data)=>{

                        // trigger the resolve
                        res({
                            data: data,
                            class: this
                        });

                    }
                });

        });

    }

    get passTimes(){

        // if pTimes is empty, or gone for some reason, do the following
        if(
            this.pTimes === undefined ||
            this.pTimes.length == 0
        ){
            // go get that promise and do stuff
            this.loadPTimes().then((obj)=>{
                
                // mom always told me I have value, and now I can prove it
                this.pTimes = obj.data;

                // send me up the chain
                return this.pTimes;
            });
        }else{

            // I always had value :), great send me up
            return this.pTimes;
        }

    }
}

,对吗?但是,当页面实际上加载台时。log触发时,当Promise/Ajax仍在运行并返回未定义时。不是我所期望的。

我试图做的是,如果触发了get函数,我们没有确定的价值;使用Ajax获取数据,然后等待该数据返回,然后再返回某些内容。

我已经通过不同的结果重写了许多不同的方式,但没有我正在寻找的结果(Console.Log返回实际的Ajax结果)。

我希望这里有人使用了类似的模式或更好的模式。在返回之前等待数据。

编辑:

也许我的问题已经足够清楚。我需要AJAX数据,当构造类或调用 get 函数时。它必须在那里。

它不能异步,因为几乎需要该数据。因此,我将请求置于承诺中,期望承诺受到尊重,并且在具有数据时将其返回 get 函数。

这没有发生,而是 get 正在等待答复时,正在返回不确定的值。

I have been banging my head against this for a while now and I can't figure it out.

I have main.js who instantiates a user object and console logs a value from it.

main.js

jsUser = new user();
console.log(jsUser.passTimes);

I then have the user.js file, which houses the class and gets the data for passTimes

user.js

class user{

    // construct the object
    constructor(obj){

        // just set stuff up, cuz why not?
        this.pTimes = [];

    }

    loadPTimes(){

        // return a promise
        return new Promise((res,rej)=>{

                $.ajax({
                    url: './data/importantfile',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        method: 'getData',
                        termCode: termCode
                    },
                    success: (data)=>{

                        // trigger the resolve
                        res({
                            data: data,
                            class: this
                        });

                    }
                });

        });

    }

    get passTimes(){

        // if pTimes is empty, or gone for some reason, do the following
        if(
            this.pTimes === undefined ||
            this.pTimes.length == 0
        ){
            // go get that promise and do stuff
            this.loadPTimes().then((obj)=>{
                
                // mom always told me I have value, and now I can prove it
                this.pTimes = obj.data;

                // send me up the chain
                return this.pTimes;
            });
        }else{

            // I always had value :), great send me up
            return this.pTimes;
        }

    }
}

Easy enough right? However, when the page actually loads the console.log triggers while the promise/ajax is still running and returns undefined. Not what I was expecting.

What I was trying to do is, if the get function is triggered and we have no established value; go get the data using ajax and wait for that data to come back before return something.

I have rewritten this so many different ways with different results, but not the result I was looking for (console.log returns the actual ajax results).

I was hoping someone here has used a similar pattern, or a better one. That waits for data before returning.

Edited:

Maybe my questions was written clearly enough. I need ajax data, when the class is constructed or when the get function is called. It has to be there.

It can't be asynchronous because that data is needed almost immediately. So I throw the request in a promise, expecting the promise to be respected and the get function to return when it has data.

This is not happening, instead get is returning undefined as a value while the ajax request is still waiting for a reply.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红玫瑰 2025-02-02 11:47:36

这应该解决您的问题:

class user{

    // construct the object
    constructor(obj){

        // just set stuff up, cuz why not?
        this.pTimes = [];

    }

    loadPTimes(){

        // return a promise
        return new Promise((res,rej)=>{

                $.ajax({
                    url: './data/importantfile',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        method: 'getData',
                        termCode: termCode
                    },
                    success: (data)=>{

                        // trigger the resolve
                        res({
                            data: data,
                            class: this
                        });

                    }
                });

        });

    }

    get passTimes(){
      return (async () => {
      
      // if pTimes is empty, or gone for some reason, do the following
        if(
            this.pTimes === undefined ||
            this.pTimes.length == 0
        ){
            // go get that promise and do stuff
            const obj = await this.loadPTimes();
            // mom always told me I have value, and now I can prove it
            this.pTimes = obj.data;
                // send me up the chain
            return this.pTimes;
           
        }else{
            // I always had value :), great send me up
            return this.pTimes;
        }

      })();
    }
}

Passtimes将回报承诺,以获取必须使用等待然后/CATCH CLASS的值。

This should fix your problem:

class user{

    // construct the object
    constructor(obj){

        // just set stuff up, cuz why not?
        this.pTimes = [];

    }

    loadPTimes(){

        // return a promise
        return new Promise((res,rej)=>{

                $.ajax({
                    url: './data/importantfile',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        method: 'getData',
                        termCode: termCode
                    },
                    success: (data)=>{

                        // trigger the resolve
                        res({
                            data: data,
                            class: this
                        });

                    }
                });

        });

    }

    get passTimes(){
      return (async () => {
      
      // if pTimes is empty, or gone for some reason, do the following
        if(
            this.pTimes === undefined ||
            this.pTimes.length == 0
        ){
            // go get that promise and do stuff
            const obj = await this.loadPTimes();
            // mom always told me I have value, and now I can prove it
            this.pTimes = obj.data;
                // send me up the chain
            return this.pTimes;
           
        }else{
            // I always had value :), great send me up
            return this.pTimes;
        }

      })();
    }
}

passTimes will return a promise so to get the value you must use await or then/catch closure

笑看君怀她人 2025-02-02 11:47:36

有一些问题:

  • 只有在 future 中可用时,就无法期望获得结果现在。因此,无论您做什么,都必须等待执行需要响应可用的逻辑。为此,您应该在然后在回调中执行该逻辑,或者使用等待暂停函数的进一步执行。

  • 您的代码创建新的Promise当您已经有一个由$。$。ajax返回的承诺时(除非您真正使用的是jQuery版本,否则十年历史)。

  • 您的代码检查长度分配给ptimes的对象的属性,但是当您返回响应时,您将普通对象分配给该属性长度属性。因此,检查该属性是错误的。

这是做您想做的众多方法之一:

class User { // Common habit to name constructors with PascalCase
    constructor(obj){
        this.pTimes = null; // It wont be an array!
    }
    async loadPTimes() {
        // Don't create a new Promise when you already have one (from $.ajax)
        const data = await $.ajax({
            url: './data/importantfile',
            type: 'post',
            dataType: 'json',
            data: {
                method: 'getData',
                termCode: termCode
            }
        });
        return this.pTimes = {
            data: data,
            class: this
        };
    }
    get passTimes() {
        return this.pTimes ?? this.loadPTimes();
    }
}

(async () => {
    var jsUser = new User(); // Declare variables with var/let/const!
    console.log(await jsUser.passTimes); // Use await
    // Anything that needs this result, should be coded here, or be called from here.
})(); // Execute the main script inside an async function, so you can use AWAIT
// Don't put any code outside the above wrapper -- except function/class definitions

There are a few issues:

  • It is impossible to expect to get a result now, when it is only available in the future. So whatever you do, you must wait with executing logic that needs the response to be available. For this you should execute that logic in a then callback, or suspend a function's further execution with await.

  • Your code creates a new Promise when you already have a promise that is returned by $.ajax (unless you really use a version of jQuery that is more than a decade old).

  • Your code checks the length property of the object assigned to pTimes, but when you get back the response, you assign a plain object to that property, which has no length property. So it is wrong to check that property.

Here is one of the many ways to do what you want:

class User { // Common habit to name constructors with PascalCase
    constructor(obj){
        this.pTimes = null; // It wont be an array!
    }
    async loadPTimes() {
        // Don't create a new Promise when you already have one (from $.ajax)
        const data = await $.ajax({
            url: './data/importantfile',
            type: 'post',
            dataType: 'json',
            data: {
                method: 'getData',
                termCode: termCode
            }
        });
        return this.pTimes = {
            data: data,
            class: this
        };
    }
    get passTimes() {
        return this.pTimes ?? this.loadPTimes();
    }
}

(async () => {
    var jsUser = new User(); // Declare variables with var/let/const!
    console.log(await jsUser.passTimes); // Use await
    // Anything that needs this result, should be coded here, or be called from here.
})(); // Execute the main script inside an async function, so you can use AWAIT
// Don't put any code outside the above wrapper -- except function/class definitions
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文