当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Are promises only for async operations?

问题描述:

I was wondering if I could use promises with my countdown timer. My code looks something like this:

function countdown(duration, callback) {

...

}

function sayHi() {

console.log('hi');

}

and I call it by doing something like

countdown(15, sayHi);

Is there a way I could do this instead?

countdown(15).then(sayHi);

Here is a JSFiddle of my current code.

网友答案:

Yes, promises are a way to "hide" callbacks. For your example, you could use promises like this:

function countdown(duration) {
    return new Promise(function (resolve, reject) {
        // wait for duration and resolve
        setTimeout(function () {
            resolve();
        }, duration);
    });
}

function sayHi() {
    console.log('hi');
}

countdown(1000).then(sayHi);
网友答案:

A promise is suitable for any operation that won't necessarily run immediately.

Javascript is single-threaded. So if you call a function, it will necessarily run immediately on the same thread. A promise is a convenient way to run code some time later (still on the same thread, but as part of a different event handler).

So in the case of a timeout, when the callback should be called later, using a promise is a good idea.

And if you're unsure whether to use a promise or a simple callback, both serve more-or-less the same purpose, but promises normally make the code more readable.

ES7 async-await is even more readable!

网友答案:
function countdown(duration) {
  return new Promise(function(resolve, reject) {
    var interval = setInterval(function() {
      console.log(duration--);
      if (!duration) {
        clearInterval(interval);
        resolve();
      }
    }, 1000);
  });
}
countdown(15).then(function() { console.log("DONE"); });
网友答案:

yes you can resolve them at your own specific time like.use closures to escape from bad response from multiple calls simultaneously.

function countdown(duration, callback) {
 var deferred = Promise.defer();
    (function(duration,deferred){setTimeout(function(){
        deferred.resolve();
    },duration);
  })(duration,deferred);
}

Previous one is outdated check this one.

  function countdown(duration, callback) {
     return new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve();
            }, duration);
        });


}
分享给朋友:
您可能感兴趣的文章:
随机阅读: