javascript - 在链式 promise 中,如果第一个 promise 要求不执行其余 promise ,如何

标签 javascript promise

我有 4 个方法,每个方法都返回一个 Promise,并且它们采用链式结构。但并不是我在第一个 Promise 中有一个可以满足的条件,所以在这种情况下我需要/不应该执行链中剩余的 Promise。我怎样才能做到这一点?

这是正在完成的 4 项任务

任务1)查看Mongo中是否存在数据,如果不存在

任务2)调用SOAP服务

任务 3) 使用 SOAP 的结果,操作数据

任务4)将此文档放入Mongo

这工作正常,但是当任务 1 有数据时,我不应该处理接下来的 3 个 Promise(任务 2、3、4)。

这是我当前的代码

checkMongoForData(req, res)
.then(function (result) {
   return makeTheSOAPcall(req, res, result)
.then(function (result) {
   return fillTheReasonDescriptions(req, res, result);
 })
 .then(function (result) {
   return upsertTheRespDocInMongo(req, res, result);
 })
 .then(function (result) {
   res.status(200);
   res.send({result: 'success', status: 200});
 })
 .catch(function (reject) {
   res.status(reject.status);
   res.send({result: reject.description, status: reject.status});
 });

//我的函数定义了类似的东西

function checkMongoForData(req, res) {
    return new Promise(function (resolve, reject) {
     // TODO : the logic goes here
     /// check to see for the data. If not there then continue
     // if there is data, no need to do remaining tasks
    });
 }

我该如何实现这一目标?谢谢。

最佳答案

How can I do this?

制作 checkMongoForData => getDataFromMongo 并在没有数据时拒绝。然后使用 catch 捕获该拒绝并触发获取数据的调用链:

getDataFromMongo(req, res)
    .catch(function() {
        // Didn't get the data, go get it
        return makeTheSOAPcall(req, res, result)
            .then(function (result) {
              return fillTheReasonDescriptions(req, res, result);
            })
            .then(function (result) {
              return upsertTheRespDocInMongo(req, res, result);
            });
    })
    .then(function (result) {
        // Got the data (one way or another)
        res.status(200);
        res.send({result: 'success', status: 200});
    })
    .catch(function (reject) {
        // Something went irretrievably wrong
        res.status(reject.status);
        res.send({result: reject.description, status: reject.status});
    });

如果 upsertTheRespDocInMongo 的分辨率值不是数据本身,您可能需要在其上添加 .then 来更改结果。

这是一个例子:

var fakeMongo = Object.create(null);

function getDataFromMongo(key) {
    console.log("getDataFromMongo: ", key);
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            if (Object.prototype.hasOwnProperty.call(fakeMongo, key)) {
                // We have the data
                resolve({key: key, value: fakeMongo[key]});
            } else {
                // We don't have the data
                reject();
            }
        }, 100);
    });
}

function makeTheSOAPcall(key) {
    console.log("makeTheSOAPcall: " + key);
    return new Promise(function(resolve) {
        resolve({
            key: key,
            value: "value for " + key
        });
    });
}

function fillTheReasonDescriptions(result) {
    console.log("fillTheReasonDescriptions: " + result.key);
    return Promise.resolve(result);
}

function upsertTheRespDocInMongo(result) {
    console.log("upsertTheRespDocInMongo: " + result.key);
    return new Promise(function(resolve) {
        fakeMongo[result.key] = result.value;
        resolve(result);
    });
}

// Usage
retrieve("key1")       // Get key1 (won't be there)
  .then(function() {
    return retrieve("key2");  // Get key2 (won't be there)
  })
  .then(function() {   // Get key1 again (will be there)
    return retrieve("key1");
  })

function retrieve(key) {
    console.log("retrieve: " + key);
    return getDataFromMongo(key/*req, res*/)
        .catch(function() {
            // Didn't get the data, go get it
            return makeTheSOAPcall(key/*req, res*/)
                .then(function(result) {
                    return fillTheReasonDescriptions(/*req, res, */result);
                })
                .then(function(result) {
                    return upsertTheRespDocInMongo(/*req, res, */result);
                });
        })
        .then(function(result) {
            // Got the data (one way or another)
            console.log("Got the data:", result);
        })
        .catch(function(reject) {
            // Something went irretrievably wrong
            console.log("Somethingw went wrong", reject);
        });
}

关于javascript - 在链式 promise 中,如果第一个 promise 要求不执行其余 promise ,如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39723989/

相关文章:

javascript - Node.js:如何从事件监听器返回值?

javascript - 带有 async/await 的 map() 函数

node.js - 尝试从 api 获取 token 时 Node 获取的错误行为

javascript - jquery '$.when' : how to trigger 'done' callback even in case of error

javascript - 等待 http.get() 的响应

javascript - 如何检查日期之间的差异

javascript - 使用溢出时隐藏滚动条 :scroll; but keep scrolling ability

javascript - ASP.NET MVC 验证不适用于 Bootstrap 模式

javascript - 如何确保在禁用时提交 <select> 表单字段?

javascript - 更改 href 以重定向