将属性附加到 Promise

Kyl*_*son 6 javascript es6-promise

关于 SO 的另一个问题激起了我创建一个setTimeout返回 Promise 和 timeId 的兴趣,但又不会破坏向后兼容性。就是我所指的问题。

_.delay它只是询问方法中的内部 return 语句underscore.js是无关的还是有目的的。这是代码块。

这是 _.delay 的代码:

// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function() { // this is to return the timerId
        return func.apply(null, args); // this guy right is in question
    }, wait);
};
Run Code Online (Sandbox Code Playgroud)

考虑到 setTimeout 目前不返回 Promise,我提出了这样的想法:它可能是为了将来的证明,以防有一天 setTimeout 返回一个 Promise。

为此,setTimeout需要返回一个timerId,以便可以取消它。因此,要返回 a,Promise您需要将timerId 附加到Promise,以便返回Promise 并且可以访问timerId。

然后,您可以修改clearTimeout为在给定 timerId 时准确执行现在的操作,但对于 Promise,它使用 Promise.timerId 来清除超时并取消 Promise。当然,取消 Promise 也需要实现......

无论如何......我开始做一些有趣的事情,并遇到了一些我无法解释的事情。如果运行下面的代码片段,您将看到 Promise.timerId在返回之前具有属性,但在返回之后该属性丢失了。谁能解释一下吗?

// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function() { // this is to return the timerId
        return func.apply(null, args); // this guy right is in question
    }, wait);
};
Run Code Online (Sandbox Code Playgroud)

tri*_*cot 5

then

pseudoSetTimeout( callback, 1000 )
    .then( ( val ) => {
      console.log( val );
    });
Run Code Online (Sandbox Code Playgroud)

返回一个新的 Promise,它不是返回的 Promise pseudoSetTimeout。这是一个具有承诺值的承诺undefined,因为then回调不返回任何内容。

then您可以通过在作业期间不申请来使其发挥作用:

pseudoSetTimeout( callback, 1000 )
    .then( ( val ) => {
      console.log( val );
    });
Run Code Online (Sandbox Code Playgroud)

因为then在 Promise 的使用中至关重要,并且经常用于链接它们,所以将自定义属性附加到 Promise 的想法似乎失去了用处。