Javascript 承诺序列 [英] Javascript Promise Sequence

查看:17
本文介绍了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;
}

推荐答案

您的代码看起来接近您在此处可以获得的最佳代码.Promises 可能是一种需要习惯的奇怪结构,尤其是在编写 promis-ified 代码通常最终会将一个函数嵌入到另一个函数中.正如你所看到的这里,这是一个漂亮的常用的用语.只有两种风格上的变化是可能的.首先, 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天全站免登陆