Promise.all忽略一项承诺,而两次调用另一项承诺

时间:2019-06-26 06:43:21

标签: javascript promise

我正在尝试使用Promise.all进行几次网络通话,然后告诉我它们何时全部完成。在我的例子中,我有三个承诺。承诺是从不同的对象返回的,但是其中两个具有相同的方法签名。第一个承诺从未执行,但第二个承诺被称为两次。如果我更改其中一种方法的名称,它会起作用,但是参数的数量似乎并不重要。代码示例:

const test = {};

test.ObjectOne = () => {
  aMethod = (paramOne, paramTwo) => new Promise((resolve, reject) => {
    resolve("Method one");
  });
  
  bMethod = (paramOne, paramTwo) => new Promise((resolve, reject) => {
    resolve("Method one two");
  });

  return this;
};

test.ObjectTwo = () => {
  aMethod = (paramOne, paramTwo) => new Promise((resolve, reject) => {
    resolve("Method two");
  });

  return this;
};

const objectOne = test.ObjectOne();
const objectTwo = test.ObjectTwo();

Promise.all([
  objectOne.aMethod(1, 2),
  objectOne.bMethod(1, 3),
  objectTwo.aMethod(1, 2),
]).then((responses) => {
  console.log(responses);
});

我希望输出为:

["Method one", "Method one two", "Method two"]

但是实际输出是:

["Method two", "Method one two", "Method two"]

我看到的是什么问题?

最诚挚的问候

2 个答案:

答案 0 :(得分:3)

您没有正确定义对象。这个:

test.ObjectTwo = () => {
  aMethod = (paramOne, paramTwo) => new Promise((resolve, reject) => {
    resolve("Method two");
  });

  return this;
};

创建一个全局变量aMethod(这将覆盖先前定义的aMethod)并返回全局对象(window)。

这是可以完成的方式:

const test = {};

test.ObjectOne = () => ({
    aMethod: (paramOne, paramTwo) => new Promise((resolve, reject) => {
        resolve("Method one");
    }),
    bMethod: (paramOne, paramTwo) => new Promise((resolve, reject) => {
        resolve("Method one two");
    })
});

test.ObjectTwo = () => ({
    aMethod: (paramOne, paramTwo) => new Promise((resolve, reject) => {
        resolve("Method two");
    })
});

const objectOne = test.ObjectOne();
const objectTwo = test.ObjectTwo();

Promise.all([
    objectOne.aMethod(1, 2),
    objectOne.bMethod(1, 3),
    objectTwo.aMethod(1, 2),
]).then((responses) => {
    console.log(responses);
});

答案 1 :(得分:1)

或者您可以通过调用promise方法来调用特定函数,而不覆盖aMethod函数

const test = {};

test.ObjectOne = () => {
  aMethod = (paramOne, paramTwo) => new Promise((resolve, reject) => {
    resolve("Method one");
  });
  
  bMethod = (paramOne, paramTwo) => new Promise((resolve, reject) => {
    resolve("Method one two");
  });

  return this;
};

test.ObjectTwo = () => {
  aMethod = (paramOne, paramTwo) => new Promise((resolve, reject) => {
    resolve("Method two");
  });

  return this;
};

const objectOne = test.ObjectOne;
const objectTwo = test.ObjectTwo;

Promise.all([
  objectOne().aMethod(1, 2),
  objectOne().bMethod(1, 3),
  objectTwo().aMethod(1, 2),
]).then((responses) => {
  console.log(responses);
});