首页 > 解决方案 > 调用内部有更多异步函数的异步函数

问题描述

我在尝试调用数组内的异步函数链时遇到了麻烦。当我单独调用该函数时,它可以正常工作,如下例所示:

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。我不在乎是否有必要安装一些插件来解决这个问题。

标签: javascriptnode.jsloopsasynchronouspromise

解决方案


在上一个异步调用完成,您必须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);
}

推荐阅读