简体   繁体   English

使用Java脚本承诺一次调用函数

[英]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”函数范围之外定义的“ dataPromise”中,因此不会在每次“ getData”调用上创建新的promise。

"getData" will invoce once and "dataPromise" will hold the first invoke data, and won't be update. “ getData”将调用一次,“ dataPromise”将保留第一个调用数据,并且不会被更新。

I want to understand if this is promise anty-pattern? 我想了解这是否是诺言anty模式? 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");});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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