Search code examples
javascriptecmascript-6es6-promise

JavaScript Promise Chaining - Issues with Template Literals


In the following code I'm chaining two JavaScript Promise(s), the first one asyncAdd(58, 12) run quite alright, while the second Promise I chained i.e return asyncAdd(res, 32); throws the given error. But it runs if I chose not to use a template literal with resolve(), i.e if I use resolve(a + b); instead of resolve(`Result for ${a} + ${b}\t= ${a + b}`);.

Is there anyway I could keep the statement in the template literal and still have my code run quite alright?

I'm sorry for any errors, it's my first time posting a question. Thanks

let asyncAdd = (a, b) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (typeof a === 'number' && typeof b === 'number') {
                resolve(`Result for ${a} + ${b}\t= ${a + b}`);
            } else {
                reject(Error('Parameters must be numbers'));
            }
        }, 1500);
    });
};

asyncAdd(58, 12)
    .then(res => {
        console.log(res);
        return asyncAdd(res, 32);
    })
    .then(res => {
        console.log(`The result should be `, res);
    })
    .catch(err => {
        console.error(err);
    });

Solution

  • I would use an object wrapper to achieve desired result:

    let asyncAdd = (a, b) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (typeof a === 'number' && typeof b === 'number') {
                    resolve({
                      value: a + b,
                      text: `Result for ${a} + ${b}\t= ${a + b}`
                    });
                } else {
                    reject(Error('Parameters must be numbers'));
                }
            }, 1500);
        });
    };
    
    asyncAdd(58, 12)
        .then(res => {
            console.log(res.text); 
            return asyncAdd(res.value, 32);
        })
       .then(res => console.log('The result should be', res.value))
       .catch(err => console.error(err));