JavaScript-可以从功能带有承诺的函数返回值
我正在学习JavaScript中的Promise,但我不明白为什么我的功能不返回正确的值。
这是我的功能:
function promise() {
let p = new Promise((resolve, reject) => {
return resolve(["a", "random", "array"]);
});
p.then((response) => {
return response;
}).catch((error) => {
return error;
});
}
console.log(promise());
如果我运行代码,我会得到不确定的
。
我认为问题在于console.log
是在返回的值之前执行的。
有人可以帮助我解决这个问题并解释这个问题吗? :)
感谢您的每一个答案。
I am learning promise in JavaScript but I don't understand why my function doesn't return the right value.
This is my function:
function promise() {
let p = new Promise((resolve, reject) => {
return resolve(["a", "random", "array"]);
});
p.then((response) => {
return response;
}).catch((error) => {
return error;
});
}
console.log(promise());
If I run the code I get undefined
.
I think the problem is that the console.log
is executed before the value of the .then
is returned.
Can somebody please help me to solve this problem and maybe explain the problem? :)
Thanks for every answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两件事:
您必须
返回
PromiseP
从Promise> Promise
函数中。您必须等待函数返回的承诺的结果,然后才能访问其满足价值:
您说您正在学习有关承诺的知识。异步/等待使所有这一切变得更加容易:
Two things:
You must
return
the promisep
from within thepromise
function.You must await the result of the promise returned by the function before you can access its fulfilled value:
You said you're learning about promises. Async/await makes all of this much easier: