in

Best way to use if/else in promise chains – JavaScript – SitePoint Forums

1682390782 cf11b3ed553d6c359d3dcc08377cc4b121fe8bf0

[ad_1]

Hello everyone-

See this SO reply for the best way to include if/else in a promise chain. The accepted solution looks like this:

new Promise(resolve => resolve({success:true}))
.then(value => {
    console.log('second block:', value);
    if (value.success) {
        //skip the rest of this chain and return the value to caller
        return value;
    }
    //do something else and continue
    return somethingElse().then(value => {
        console.log('3rd block:', value);
        return value;
    });
}).then(value => {
    //The caller's chain would continue here whether 3rd block is skipped or not
    console.log('final block:', value);
    return value;
});

I’ve played around with it and this seems to work. :blush:

Note the syntax with two return remarks (interesting)

*return* somethingElse().then(value => {
    console.log('3rd block:', value);
    *return* value;
});

Is this the recommended way to embed if/else into js promise chains?

I found another old SO solution here, but this one seems to create too much unnecessary stuff function statement.

(Why are promises so hard to master? Don’t answer…)

I don’t understand why you use success in resolution returns? That’s why you have resolution and rejection. For me, resolve is called only if success is true, reject is called otherwise.



1 like

        return new Promise((resolve, reject) => {
            xhr.open(options.method || 'get', url, true);

            xhr.upload.addEventListener('progress', options.onProgress || (() => {
            }));

            xhr.addEventListener('load', () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    resolve(xhr.responseText);
                } else {
                    reject(new Error(xhr.statusText));
                }
            });

            xhr.addEventListener('error', () => reject(new Error(xhr.statusText)));
            xhr.addEventListener('abort', () => reject(new Error('Request aborted')));

            xhr.send(options.body);
        });

It’s very easy for me.

[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    129487374 bigissue

    Big Issue North to cease production in May

    2021 renault 5 prototype Featured Gear

    Renault 5 EV 2024 Prototype Drive: Gripping Stuff