承诺JavaScript代码说明中的延迟功能

JS情人

我没有问如何编写延迟函数,因为已经回答了这个问题,我只是不了解代码本身。我不明白为什么我们需要让一个函数返回另一个函数?我们如何获得用
注释注释代码的数据如果您在控制台中运行它,它将正常工作。我只是在寻找新手的解释,以了解为什么我们在这里需要这种简单易用的语法。

// a function
function delay(duration) {
  // why do we return here !! 
  // this args are the data.json() 
  // but how do we have access to it?? I don't see anywhere in the code that we are calling delay(data => data.json())
  // I know that .then calls the function for you with data.json() but that only if the function doesn't have a paramets for example doing just then(delay) but we are using a paramaeter here which is the 1000
  return function(...args){
    // so we return a new promise that resolves after sometime, this make sense.
    // but I don't understand all these returns.
    return new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve(...args);
      }, duration)
    });
  };
}


const endpoint = 'https://pokeapi.co/api/v2/pokemon/ditto/'
const prom1 = fetch(endpoint)
              .then(data => data.json())
              .then(delay(2000))
              .then(console.log)


TJ人群

...为什么我们需要让一个函数返回另一个函数?

这样当你做

.then(delay(2000))

...它调用 delay(2000),获取将添加该延迟的函数,并将其添加到Promise链中。稍后,当链建立时,该函数将使用参数thencallback接收(实现值)来调用,该函数将其作为其...argsrest参数中的唯一条目接收然后它将等待duration毫秒,然后再以该实现值履行其承诺并允许链继续运行。

如果delay直接返回其承诺,则该承诺将到达then并且超时将过早开始(在实现到达链中的那个点之前)。它还会“吃掉”通过链传递的实现价值,因为在履行其诺言时就不会使用该价值。

如果您刚刚:

function delay(duration, ...args) {
  return new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve(...args);
    }, duration)
  });
}

那么您必须像这样使用它:

.then(delay.bind(null, 2000))

这比较尴尬(并且仍然可以创建并提供功能,因为那样bind做)。


旁注:该delay实现没有理由使用休息和传播。仅使用的第一个参数resolve(其他任何参数都将被完全忽略),并且then处理程序仅会收到一个参数。因此可能是:

function delay(duration) {
  return function(fulfillmentValue){
    return new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve(fulfillmentValue);
      }, duration)
    });
  };
}

...尽管我可能会对所有三个函数delay创建都使用箭头函数

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章