简体   繁体   中英

Is there a way to return a promise to .catch and .then

Basically I want to run the same code regardless if the code throws an error or not. Now I'm doing this:

.then((resp) => {
    assert(false);
}, err => {
    assert.equal(2, err.error.errors.length);
    });
});

But I would like to do something like this:

.something((resp, err) => {
    assert.equal(400, resp.statusCode)
    assert.equal(2, err.error.errors.length);
}

You can do it...

...just use catch and return something from it, then use then on the promise .catch returns:

thePromise
    .catch(err => err)
    .then(resultOrError => {
        // Your code
    });

The argument your then callback receives ( resultOrError in the above) will be the resolved value if the promise was resolved, or the rejected value (loosely, "error") if it was rejected. You can naturally do something more in catch if you want to differentiate them.

Example (run it a few times, you'll see it get resolved, and also rejected):

 let p = new Promise((resolve, reject) => { setTimeout(() => { if (Math.random() < 0.5) { resolve("success"); } else { reject("error"); } }, 0); }); p.catch(err => err).then(resultOrError => { console.log("Got this:", resultOrError); }); 

...but alternately

...you can just have aa common function both callbacks call, after using the resolved value or the rejected value:

function doSomethingNoMatterWhat() {
    // ...
}

thePromise
    .then(result => {
        // Presumably use `result`, then:
        doSomethingNoMatterWhat();
    })
    .catch(error => {
        // Presumably use `error`, then:
        doSomethingNoMatterWhat();
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM