簡體   English   中英

JavaScript Promise鏈接-模板文字問題

[英]JavaScript Promise Chaining - Issues with Template Literals

在下面的代碼中,我鏈接了兩個JavaScript Promise,第一個asyncAdd(58, 12)運行得很好,而我鏈接的第二個Promise即return asyncAdd(res, 32); 拋出給定的錯誤。 但是如果我選擇不使用帶有resolve()的模板文字,它就會運行,即如果我使用resolve(a + b); 而不是resolve(`Result for ${a} + ${b}\\t= ${a + b}`);

無論如何,我可以將語句保留在模板文字中,而我的代碼仍然運行正常嗎?

對於任何錯誤,我們深感抱歉,這是我第一次發布問題。 謝謝

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);
    });

我將使用對象包裝器來達到所需的結果:

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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM