[英]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 ie return asyncAdd(res, 32);
在下面的代码中,我链接了两个JavaScript Promise,第一个
asyncAdd(58, 12)
运行得很好,而我链接的第二个Promise即return asyncAdd(res, 32);
throws the given error. 抛出给定的错误。 But it runs if I chose not to use a template literal with
resolve()
, ie if I use resolve(a + b);
但是如果我选择不使用带有
resolve()
的模板文字,它就会运行,即如果我使用resolve(a + b);
instead of resolve(`Result for ${a} + ${b}\\t= ${a + b}`);
而不是
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);
});
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.