简体   繁体   中英

Using java script promises for calling function once

  var dataPromise= $q.defer();

  function getDataPromise(){
    return dataPromise.promise;
  }

  (function getData(){
    setTimeOut(
       function(){
          myPromise.resolve("data");
       }
      ,1000);
  })();

   getDataPromise().then(function(){alert("use old data");});

In this code "dataPromise" defined out of "getData" function scope, therefor new promise won't be created on each "getData" invocation.

"getData" will invoce once and "dataPromise" will hold the first invoke data, and won't be update.

I want to understand if this is promise anty-pattern? if so - what is the correct way to call async function once?

Here's how I would write it:

const dataPromise = $q(function(resolve) {
    setTimeOut(function() {
        resolve("data");
    }, 1000);
});

function getDataPromise() {
    return dataPromise;
}

getDataPromise().then(function(){alert("use old data");});

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