javascript - 调用内部有更多异步函数的异步函数
问题描述
我在尝试调用数组内的异步函数链时遇到了麻烦。当我单独调用该函数时,它可以正常工作,如下例所示:
function consoleAll(string) {
return new Promise(function (resolve) {
console1(string).then(function () {
console2(string).then(function () {
resolve();
});
});
});
}
function console1(value) {
return new Promise((resolve) => {
console.log(value + "1");
resolve()
});
}
function console2(value) {
return new Promise((resolve) => {
console.log(value + "2");
resolve()
});
}
consoleAll('value-')
在这种情况下,结果如下是正确的:
value-1
value-2
但是当它在循环中传递时,它不会正确地使线程并完全无序地调用函数
function consoleAll(string) {
return new Promise(function (resolve) {
console1(string).then(function () {
console2(string).then(function () {
resolve();
});
});
});
}
function console1(value) {
return new Promise((resolve) => {
console.log(value + "1");
resolve()
});
}
function console2(value) {
return new Promise((resolve) => {
console.log(value + "2");
resolve()
});
}
//Call
['h1-', 'h2-', 'h3-'].forEach(function (string) {
consoleAll(string)
});
这次不是写下面的结果:
h1-1
h1-2
h2-1
h2-2
h3-1
h3-2
它输出这个:
h1-1
h2-1
h3-1
h1-2
h2-2
h3-3
看起来它为整个数组调用了console1函数,然后调用了console2。
有谁知道打这个电话的正确方法?PS。我不在乎是否有必要安装一些插件来解决这个问题。
解决方案
在上一个异步调用完成后,您必须logAll
再次调用:
const values = ['h1-', 'h2-', 'h3-'];
(function next(i) {
if(i >= values.length) return;
consoleAll(values[i]).then(function() {
next(i + 1);
});
})(0);
或者,如果这很难看,这是一种更现代的方式:
(async function() {
for(const string of ["h1-", "h2-", "h3"])
await consoleAll(string);
})();
正如我在评论中指出的那样,consoleAll
最好写成:
function consoleAll(str) {
return console1(str).then(function() {
return console2(str);
});
}
或者:
async function consoleAll(str) {
await console1(str);
await console2(str);
}
推荐阅读
- javascript - Javascript:如何计算到一个特定的数字?
- python - 聊天机器人使用 pdf 文档作为源
- android - 如何在 Android 中使用 Dagger 2 从应用程序组件中获取对象?
- sql - 如何从列中获取特定模式
- ios - 尝试向左或向右滚动屏幕时 UIScrollView 崩溃
- angular - Angular - 无效的日期时间格式:1292 日期值不正确
- ruby - 不确定如何将当前元素编码为假
- jquery - 当窗口的高度变小时添加一个css(每次窗口重新调整大小)
- gradle - Jacoco 报告没有被推送到 SonarCloud
- python - 如何在 R 或 Python 中创建类似于我在 Excel 中创建的数据透视表?