首页 > 解决方案 > 如何序列化返回 Promises 的 Javascript 函数数组?

问题描述

我的问题与此非常相似,但我无法让它工作:(

问题:

  1. 我有一个需要在 IE11 和 Chrome 中运行的 Javascript 程序。

  2. 它有一个我需要按顺序执行的功能列表。

  3. 每个函数都返回一个 Promise。Promise.all(promisesArray)工作到我可以“等待”直到所有功能完成后再继续。但它不保证每个函数都按顺序运行。这是必不可少的。

  4. 我试过使用Array.prototype.reduce(),但我无法弄清楚如何正确使用它。

  5. 因为需要在 IE11 中运行,所以不能使用“箭头函数”之类的 ES6 特性。

这是我的代码:

<script>
var fn = function(arg) {
  return new Promise (function (resolve, reject) {
    console.log("fn(" + arg + ")...");
    resolve("OK");
  });
}

var p = fn("A").then(function(r) {
  console.log("promise resolved: " + r + ".");
})

var chain = [];
chain.push(fn("3"));
chain.push(fn("1"));
chain.push(fn("2"));
console.log("Built chain:", chain);
Promise.all(chain);

chain.length = 0;
chain[2] = fn("30");
chain[1] = fn("20");
chain[0] = fn("10");
chain.reduce(function(promise, item) {
  return promise.then(function() {
    console.log("then:", item);
  }), Promise.resolve();
});
console.log("Done.");
</script>;

我需要按顺序执行的功能array[0], array[1], array[2]

标签: javascriptes6-promise

解决方案


你真的很接近你的减速器!

reducer 的初始值为Promise.resolve(),所以当第一次调用该函数时:

chain.reduce(function(promise, item) {
//                    ^^ promise is a resolved promise,
//                             ^^ item is chain[0]
  return promise.then(function() {
    console.log("then:", item);
    //           ^^ when the promise resolves (immediately) this is called
    //              BUT no value is returned.
  }), Promise.resolve();

});

将此与手动链接承诺进行比较。你会返回下一个等待的承诺:

Promise.resolve()
  .then(item => { console.log("then: ", item); return fn("10"); })
  .then(item => { console.log("then: ", item); return fn("20"); })
  .then(item => { console.log("then: ", item); return fn("30"); })

看看减速机怎么这么近?我们只想返回一个承诺:

var chain = [fn("10"), fn("20"), fn("30")];

chain.reduce(function(promise, item) {
  return promise.then(function() {
    console.log("then:", item);
    return item;
  }), Promise.resolve();
});

编辑
如果fn呼叫开始工作,这些分配中的每一个都将无序启动呼叫:

chain.length = 0;
chain[2] = fn("30");
chain[1] = fn("20");
chain[0] = fn("10");

要按您想要的顺序运行每个fn,您必须将调用推迟fn到上一个调用解决之前。我们在上面的手动示例中做到了这一点。根据您的数据的复杂程度,您可以减少参数数组fn或将每个调用包装在一个不会运行的函数中:

[10,20,30]
  .reduce(function(promise, arg) {
    return promise.then(function() {
      return fn(arg);
    }), Promise.resolve();
  });

[function() { return fn(10); }, function() { return fn(20) }, function() { return fn(30) }]
  .reduce(function(promise, callFn) {
    return promise.then(function() {
      return fn(callFn);
    }), Promise.resolve();
  });

推荐阅读