简体   繁体   中英

Is it an anti pattern that Promise with resolve and reject as property?why?

export function getDeferred () {
    let resolve; let reject;
    const promise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
    });

    promise.resolve = resolve;
    promise.reject = reject;
    return promise ;
};


let deferred=getDeferred();

async function fetchSomeData(){
    let data=await fetch('...')
    deferred.resolve(data);
}

async function someFunctionMustHaveFetchedData(){
    let data = await deferred;
    // do something after deferred resolved
}



why am i doing this?
someFunctionMustHaveFetchData will be called many times but data should only be fetch once

It's probably not an "anti-pattern" per se, but I would only expose reject and resolve if you absolutely have to. Which is not the case here. You can just store the promise or the data in a variable:

let promise;

async function someFunctionMustHaveFetchedData(){
    if (!promise) {
      promise = fetch('...');
    }
    let data = await promise;
    // do something after deferred resolved
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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