18910140161

JavaScript-来自多个文件的一个承诺-堆栈溢出

顺晟科技

2022-10-18 14:12:26

156

下面

的示例显示了我的应用程序的一个片段。假设是:一些函数在文档加载后执行,另一些仅在POST响应后执行。在这个MOMET上,回调被放置在数组中,并在请求完成后执行。一切都和预期的一样。我想把这些回调改成一个承诺,它会像现在一样被解雇";update.endRequest()";我想知道这是否可能?欢迎提出任何建议。或者一个想法,如果它可以做得更好。

更新.JS

class UpdateClass {
    constructor() {
        this.callbacks = [];
    }

    success(callback) {
        this.callbacks.push(callback);
    }

    endRequest() {
        this.callbacks.forEach(callback => callback());
    }
}

const Update = new UpdateClass();
export default Update;

文件1.

JS
import Update from './update';

export default class File1Class {
    constructor () {
        this.init();
    }

    init() {
        Update.success(this.update);

        exampleFunction();
    }

    update() {
        exampleFunctionAfterUpdate();
    }
}

function exampleFunction() {
    console.log('On document load 1');
}

function exampleFunctionAfterUpdate() {
    console.log('After Update 1');
}

文件2.

JS
import Update from './update';

export default class File2Class {
    constructor () {
        this.init();
    }

    init() {
        Update.success(this.update);

        anotherExampleFunction();
    }

    update() {
        anotherExampleFunctionAfterUpdate();
    }
}

function anotherExampleFunction() {
    console.log('On document load 2');
}

function anotherExampleFunctionAfterUpdate() {
    console.log('After Update 2');
}

应用程序.JS

import Update from './update';
import File1Class from './file1';
import File2Class from './file2';

class AppClass {
    constructor () {
        this.init();
    }
    
    init() {
        new File1Class();
        new File2Class();
        
        triggerfunction();
    }
}

function triggerfunction() {
    const button = document.getElementById('trigger');
    
    button.addEventListener('click', () => {
        xhr.open('POST', 'someUrl', true);
        xhr.onload = () => {
            if (xhr.status === 200) {
                Update.endRequest();
            }
        };
        xhr.send(someJsonData);
    });
}

window.app = new AppClass();

顺晟科技:

你可以用这样

的东西。

const promiseObj = new Promise((resolve,reject)=>{
  exampleFunctionAfterUpdate();
  anotherExampleFunctionAfterUpdate();
  resolve(true);
});

function triggerfunction() {
    const button = document.getElementById('trigger');
    
    button.addEventListener('click', () => {
        xhr.open('POST', 'someUrl', true);
        xhr.onload = () => {
            if (xhr.status === 200) {
                // Update.endRequest();
                promiseObj.then(()=> console.log('Functions executed'));
            }
        };
        xhr.send(someJsonData);
    });
}

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航