Javascript承诺序列 [英] Javascript Promise Sequence

查看:106
本文介绍了Javascript承诺序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在序列中处理许多承诺。我下面有一个工作代码,但我想知道我是否已经复制了承诺的链接。我似乎正在创造大量的新关闭,我正在抓住我的头脑,想知道我是否缺少某些东西。

I want to process a number of promises in Sequence. I have a working piece of code below but I'm wondering if I have over complicated the chaining of promises. I seem to be creating a great deal of new closures and I'm scratching my head wondering if I'm missing something.

有没有更好的方式来写这个功能:

Is there a better way to write this function:

'use strict';
addElement("first")
.then(x => {return addElement("second")})
.then(x => { return addElement("third")})
.then(x => { return addElement("fourth")})   

function addElement(elementText){
    var myPromise = new Promise(function(resolve,reject){
        setTimeout(function(){
            var element=document.createElement('H1');
            element.innerText = `${elementText} ${Date.now()}`;
            document.body.appendChild(element);
            resolve();
        }, Math.random() * 2000);
    });
return myPromise;
}


推荐答案

您的代码看起来接近最好你可以到这里。承诺可能是一个奇怪的结构来习惯,特别是写作promis-ified代码通常可能最终嵌入功能在另一个功能。正如你可以看到 here ,这是一个漂亮的常用的措辞使用。只有两种风格的变化才有可能发生。首先, myPromise 是不必要的,仅用于添加一些混乱的额外代码行。只是直接退回承诺更简单。其次,您可以使用功能绑定来简化您的调用。它可能不在函数内部,但它确实消除了几个闭包。这两个更改如下所示:

Your code looks close to the best you can get here. Promises can be a strange structure to get used to, especially as writing promis-ified code can often end up embedding a function in another function. As you can see here, this is a pretty common phrasing to use. There are only two stylistic changes that could possibly be made. Firstly, myPromise is unnecessary and only serves to add a confusing extra line of code. It's simpler just to return the promise directly. Secondly, you can use function binding to simplify your calls at the beginning. It may not be inside the function itself, but it does eliminate several closures. Both changes are shown below:

'use strict';
addElement("first")
.then(addElement.bind(null,"second"))
.then(addElement.bind(null,"third"))
.then(addElement.bind(null,"fourth"))   

function addElement(elementText){
    return new Promise(function(resolve,reject){
        setTimeout(function(){
            var element=document.createElement('H1');
            element.innerText = `${elementText} ${Date.now()}`;
            document.body.appendChild(element);
            resolve();
        }, Math.random() * 2000);
    });
}

值得一提的是,如果您愿意重组一下,稍微更有吸引力的设计将采取以下形式:

It's worth pointing out that, if you were willing to restructure a bit, a slightly more attractive design would take form:

'use strict';
var myWait = waitRand.bind(null,2000);
myWait
  .then(addElement.bind(null, "first"))
  .then(myWait)
  .then(addElement.bind(null, "second"))
  .then(myWait)
  .then(addElement.bind(null, "third"))

function waitRand(millis) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, Math.random() * millis);
  }
}

function addElement(elementText) {
  var element = document.createElement('h1');
  element.innerText = `${elementText} ${Date.now()}`;
  document.body.appendChild(element);
}

为了清晰起见,这个交易长度的承诺链,以及略少嵌套级别。

This trades length of promise chain for clarity, as well as having slightly fewer nested levels.

这篇关于Javascript承诺序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆