函数内部promise的返回值是如何工作的(第一次学习js)
我最近开始学习JS,并看到了关于承诺的教程,在一项手练习期间,我尝试写自己的诺言。
function isEven(number){
return new Promise((resolve,reject)=>{
res = "";
if(isNaN(number)){
reject();
return res;
}
else{
if(number%2 == 0){
res= "Even";
}
res = "odd";
resolve();
return res;
}
})
}
var num = 45
let str = isEven(num).then(()=>{
console.log("succesfull");
}).catch(()=>{
console.log("NAN");
})
document.getElementById('number').innerHTML = str;
我得到的响应[Object Promise]
。我想访问通过函数返回的str值,请有人帮助我理解这个概念
I recently started learning JS and saw a tutorial on promises, and during a handson exercise i tried writing my own promise.
function isEven(number){
return new Promise((resolve,reject)=>{
res = "";
if(isNaN(number)){
reject();
return res;
}
else{
if(number%2 == 0){
res= "Even";
}
res = "odd";
resolve();
return res;
}
})
}
var num = 45
let str = isEven(num).then(()=>{
console.log("succesfull");
}).catch(()=>{
console.log("NAN");
})
document.getElementById('number').innerHTML = str;
and the response i got [object Promise]
. I want to access the str value which is returned through function isEven , kindly someone help me to understand this concept
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是,当您在某些条件下解决/拒绝承诺时,没有与该操作相关的值。您需要将您想要获取的任何内容传递给这些方法,如下所示:
如果您在 Promise 上使用
.then
,它会自动假设所述 Promise 将解析,并将解析后的值作为任何回调函数的输入你放进去Your problem is that, while you're resolving/rejecting the promise under certain conditions, there are no values associated with that action. You need to pass whatever you want to grab to those methods as below:
If you use the
.then
on a Promise it auto assumes that said Promise will resolve, taking that resolved value as input for whatever callback function you're putting inside