javascript - 如何序列化返回 Promises 的 Javascript 函数数组?
问题描述
我的问题与此非常相似,但我无法让它工作:(
问题:
我有一个需要在 IE11 和 Chrome 中运行的 Javascript 程序。
它有一个我需要按顺序执行的功能列表。
每个函数都返回一个 Promise。
Promise.all(promisesArray)
工作到我可以“等待”直到所有功能完成后再继续。但它不保证每个函数都按顺序运行。这是必不可少的。我试过使用
Array.prototype.reduce()
,但我无法弄清楚如何正确使用它。因为需要在 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]
。
解决方案
你真的很接近你的减速器!
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();
});
推荐阅读
- python - 流利的python FrenchDeck 1.1
- mysql - 我可以将mysql日期默认值设置为空值吗?
- javascript - Puppeteer - 如何更改文档中某些页面的方向?
- google-apps-script - 如何从数据验证单元格中对 2 种不同的方式进行排序
- c++ - 将枚举类变量保存到 JSON
- vim - gvim81的菜单中不显示任何字符
- kubernetes - 如何在 Pod Secret 出现后创建 Pod 的依赖项
- java - 使用 Logback SSLSocketAppender 时 Splunk 日志显示为十六进制
- android - BottomNavigationView 的每个页面中的多个 Fragment
- mysql - 如何每小时访问不同机器的mysql表数据?