本机Javascript中的链接承诺

追逐者

我想将3个诺言链接在一起,但是关于resolvereject功能,有些行为我无法弄清楚我简化了我的代码,以问这个问题:

function testP(num) {
  return new Promise((resolve, reject) => {
    console.log('Do Work', num);
    reject(num);
  });
}

function testPromises() {
  return new Promise((resolve, reject) => {
      testP(1)
        .then(testP(2))
        .then(testP(3))
        .then(resolve)
        .catch(reject);
  });
};

const theTest = testPromises().then(()=>{
    console.log("all done");
}).catch(err => {
    console.log("ERR", err);
});

我在输出中看到的是:

Do Work 1
Do Work 2
Do Work 3
ERR 1

为什么代码会到达,Do Work 2并且Do Work 3第一个诺言reject立即生效?我的理解是,该then功能等待承诺resolvereject执行前。

TJ人群

因为当你做

.then(testP(2))

立即无条件调用 testP,传入2,然后将其返回值传递到中.then,方法与foo(bar()) 调用 bar并将其返回值传递到中的方式完全相同foo

这段代码:

  testP(1)
    .then(testP(2))
    .then(testP(3))
    .then(resolve)
    .catch(reject);

的评估方式如下(省略了一些次要细节):

  • 调用testP值1并将结果值记为p1
  • testP以值2呼叫
  • p1.then用该调用的结果进行调用,并将结果值记为P2
  • 呼叫testP值3
  • p2.then用该调用的结果进行调用,并将结果值记为p3
  • 调用p3.then该值resolve并将结果记为p4
  • p4.catch用值调用reject
  • 调用reject第一次调用函数testP与值1
  • 用值1调用rejectfromtestPromises

如果您希望testP等到第一个解决之后,就不调用它,而是传递对它的引用:

.then(testP)

如果希望加入参数,请使用bind

.then(testP.bind(null, 2))

或内联函数:

.then(function() {
    return testP(2);
 })

示例(需要使用的浏览器Promise

function testP(num) {
  return new Promise((resolve, reject) => {
    console.log('Do Work', num);
    reject(num);
  });
}

function testPromises() {
  return new Promise((resolve, reject) => {
      testP(1)
        .then(testP.bind(null, 2))
        .then(testP.bind(null, 3))
        .then(resolve)
        .catch(reject);
  });
};

const theTest = testPromises().then(()=>{
    console.log("all done");
}).catch(err => {
    console.log("ERR", err);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章