Is it safe to resolve a promise multiple times?

前端 未结 7 854
旧时难觅i
旧时难觅i 2021-01-31 06:33

I have an i18n service in my application which contains the following code:

var i18nService = function() {
  this.ensureLocaleIsLoaded = function() {
    if( !th         


        
7条回答
  •  星月不相逢
    2021-01-31 07:09

    There s no clear way to resolve promises multiple times because since it's resolved it's done. The better approach here is to use observer-observable pattern for example i wrote following code that observes socket client event. You can extend this code to met your need

    const evokeObjectMethodWithArgs = (methodName, args) => (src) => src[methodName].apply(null, args);
        const hasMethodName = (name) => (target = {}) => typeof target[name] === 'function';
        const Observable = function (fn) {
            const subscribers = [];
            this.subscribe = subscribers.push.bind(subscribers);
            const observer = {
                next: (...args) => subscribers.filter(hasMethodName('next')).forEach(evokeObjectMethodWithArgs('next', args))
            };
            setTimeout(() => {
                try {
                    fn(observer);
                } catch (e) {
                    subscribers.filter(hasMethodName('error')).forEach(evokeObjectMethodWithArgs('error', e));
                }
            });
    
        };
    
        const fromEvent = (target, eventName) => new Observable((obs) => target.on(eventName, obs.next));
    
        fromEvent(client, 'document:save').subscribe({
            async next(document, docName) {
                await writeFilePromise(resolve(dataDir, `${docName}`), document);
                client.emit('document:save', document);
            }
        });
    

提交回复
热议问题