在将Promise与Non-Promise调用链接时如何避免传播

我希望以下代码不要调用OK逻辑,也不要拒绝诺言。注意,我混合了promise和non-promise调用(在从其non-promise步骤返回一个字符串后,它仍然设法保持thenable),我只希望promise停留在{{1} }状态,如果pending解析为非OK值。

p1
orez99 回答:在将Promise与Non-Promise调用链接时如何避免传播

您有两个选择:

1)引发错误:

p1.then(result => {
  if (result =='notOk') {
    throw new Error('not ok');
  } else {
    return 'OK';
  }
})
.then(r => {
  // r will be 'OK'
})
.catch(e => {
  // e will be an error with message 'not ok',if it threw
})

第二个.then将不运行,.catch将运行。

2)有条件地决定在后者.then中做什么:

p1.then(result => {
  if (result =='notOk') {
    return 'not ok'
  } else {
    return 'OK';
  }
})
.then(r => {
  if (r === 'OK') {
    // do stuff here for condition of OK
  }
})

之所以有效,是因为第二个.then将前一个.then返回的内容作为参数(但是,如果前一个.then返回了Promise,则第二个.then的参数将是异步解析的结果) )

请注意:如果您.catch犯了一个错误的诺言,并且返回了那个诺言,那么最终的诺言就不会有错误,因为.catch抓住了它。

,

最好的方法是不要那样链接。而是这样做:

const p1 = new Promise((resolve,reject) => {
    resolve("NOT_OK_BUT_NOT_A_CATCH_NEITHER");
});

p1.then(result => {
    if (result !== "OK") {
        return "How do I avoid calling OK logic w/out rejecting?";
    } else {
        return Promise.resolve("OK")
            .then(result => {
                console.error("OK logic...");
            });
    }
})

如果要编写线性链,则表示要逐步执行,在这种情况下,这不是您想要的。

或者,如果您的目标平台/构建系统支持它,则将其编写为异步函数:

(async function() {
    const result = await Promise.resolve "NOT_OK_BUT_NOT_A_CATCH_NEITHER");

    if (result !== "OK") {
        return "How do I avoid calling OK logic w/out rejecting?";
    } else {
        await Promise.resolve("OK");

        console.error("OK logic...");
    }
})();
,

找到了一种方法,不确定它有多好,但它能起作用。这个想法是一路实现承诺,只是在不需要时不解决。

就我而言,这为我节省了管理可忽略结果的麻烦,而不会像points这样的标志污染结果。

form_fields
本文链接:https://www.f2er.com/3081193.html

大家都在问