如何从 setTimeout 做出承诺

2022-08-30 04:20:23

这不是一个现实世界的问题,我只是想了解承诺是如何创造的。

我需要了解如何为不返回任何内容的函数做出承诺,例如setTimeout。

假设我有:

function async(callback){ 
    setTimeout(function(){
        callback();
    }, 5000);
}

async(function(){
    console.log('async called back');
});

如何创建一个可以在准备就绪后返回的承诺?asyncsetTimeoutcallback()

我以为包装它会把我带到某个地方:

function setTimeoutReturnPromise(){

    function promise(){}

    promise.prototype.then = function() {
        console.log('timed out');
    };

    setTimeout(function(){
        return ???
    },2000);


    return promise;
}

但我不能超越这一点。


答案 1

更新 (2017)

在2017年,Promises内置于JavaScript中,它们是由ES2015规范添加的(polyfill可用于IE8-IE11等过时的环境)。它们使用的语法使用您传递到构造函数(执行器)中的回调,该回调接收用于解析/拒绝承诺作为参数的函数。PromisePromise

首先,由于异步现在在JavaScript中具有含义(即使它在某些上下文中只是一个关键字),我将用作函数的名称以避免混淆。later

基本延迟

使用原生 promise(或忠实的 polyfill),它看起来像这样:

function later(delay) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay);
    });
}

请注意,这假设其版本符合浏览器的定义,除非您在间隔后给出任何参数,否则不会向回调传递任何参数(这在非浏览器环境中可能不是真的,在Firefox上以前不是这样,但现在是正确的;在Chrome上是这样,甚至在IE8上也是如此)。setTimeoutsetTimeout

带值的基本延迟

如果您希望您的函数可以选择性地传递分辨率值,在任何模糊的现代浏览器上,允许您在延迟后提供额外的参数,然后在调用时将这些参数传递给回调,则可以执行此操作(当前的Firefox和Chrome;IE11+,大概是Edge;IE8 或 IE9,对 IE10 一无所知):setTimeout

function later(delay, value) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
        /* Or for outdated browsers that don't support doing that:
        setTimeout(function() {
            resolve(value);
        }, delay);
        Or alternately:
        setTimeout(resolve.bind(null, value), delay);
        */
    });
}

如果您使用的是ES2015+箭头函数,则可以更简洁:

function later(delay, value) {
    return new Promise(resolve => setTimeout(resolve, delay, value));
}

甚至

const later = (delay, value) =>
    new Promise(resolve => setTimeout(resolve, delay, value));

可取消的延迟与价值

如果要使取消超时成为可能,则不能只从 返回承诺,因为无法取消承诺。later

但是,我们可以轻松地返回一个带有承诺的方法和访问器的对象,并在取消时拒绝承诺:cancel

const later = (delay, value) => {
    let timer = 0;
    let reject = null;
    const promise = new Promise((resolve, _reject) => {
        reject = _reject;
        timer = setTimeout(resolve, delay, value);
    });
    return {
        get promise() { return promise; },
        cancel() {
            if (timer) {
                clearTimeout(timer);
                timer = 0;
                reject();
                reject = null;
            }
        }
    };
};

实际示例:

const later = (delay, value) => {
    let timer = 0;
    let reject = null;
    const promise = new Promise((resolve, _reject) => {
        reject = _reject;
        timer = setTimeout(resolve, delay, value);
    });
    return {
        get promise() { return promise; },
        cancel() {
            if (timer) {
                clearTimeout(timer);
                timer = 0;
                reject();
                reject = null;
            }
        }
    };
};

const l1 = later(100, "l1");
l1.promise
  .then(msg => { console.log(msg); })
  .catch(() => { console.log("l1 cancelled"); });

const l2 = later(200, "l2");
l2.promise
  .then(msg => { console.log(msg); })
  .catch(() => { console.log("l2 cancelled"); });
setTimeout(() => {
  l2.cancel();
}, 150);

2014年的原始答案

通常你会有一个承诺库(一个是你自己写的,或者是几个中的一个)。该库通常有一个对象,您可以创建该对象并在以后“解析”该对象,并且该对象将具有您可以从中获得的“承诺”。

然后往往会看起来像这样:later

function later() {
    var p = new PromiseThingy();
    setTimeout(function() {
        p.resolve();
    }, 2000);

    return p.promise(); // Note we're not returning `p` directly
}

在对这个问题的评论中,我问:

您是否正在尝试创建自己的承诺库?

你说

我不是,但我想现在这实际上是我试图理解的。图书馆将如何做到这一点

为了帮助理解,这里有一个非常非常基本的例子,它不是远程承诺 - A兼容:实时复制

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
  <script>
    (function() {

      // ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
      var PromiseThingy = (function() {

        // Internal - trigger a callback
        function triggerCallback(callback, promise) {
          try {
            callback(promise.resolvedValue);
          }
          catch (e) {
          }
        }

        // The internal promise constructor, we don't share this
        function Promise() {
          this.callbacks = [];
        }

        // Register a 'then' callback
        Promise.prototype.then = function(callback) {
          var thispromise = this;

          if (!this.resolved) {
            // Not resolved yet, remember the callback
            this.callbacks.push(callback);
          }
          else {
            // Resolved; trigger callback right away, but always async
            setTimeout(function() {
              triggerCallback(callback, thispromise);
            }, 0);
          }
          return this;
        };

        // Our public constructor for PromiseThingys
        function PromiseThingy() {
          this.p = new Promise();
        }

        // Resolve our underlying promise
        PromiseThingy.prototype.resolve = function(value) {
          var n;

          if (!this.p.resolved) {
            this.p.resolved = true;
            this.p.resolvedValue = value;
            for (n = 0; n < this.p.callbacks.length; ++n) {
              triggerCallback(this.p.callbacks[n], this.p);
            }
          }
        };

        // Get our underlying promise
        PromiseThingy.prototype.promise = function() {
          return this.p;
        };

        // Export public
        return PromiseThingy;
      })();

      // ==== Using it

      function later() {
        var p = new PromiseThingy();
        setTimeout(function() {
          p.resolve();
        }, 2000);

        return p.promise(); // Note we're not returning `p` directly
      }

      display("Start " + Date.now());
      later().then(function() {
        display("Done1 " + Date.now());
      }).then(function() {
        display("Done2 " + Date.now());
      });

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

答案 2
const setTimeoutAsync = (cb, delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(cb());
    }, delay);
  });

我们可以像这样传递自定义的“cb fxn”