我正在尝试使用 async-await 和 promise 来理解以下 2 个示例函数。
我希望这两个函数都返回“输出”,但使用 promise 的函数返回一个未定义的。
为什么会这样?我已经在 promise.resolve().then() 中返回了值,但毕竟没有返回任何值。
我在处理我的项目时遇到了这个问题。我正在使用 promise 方法返回一个值,但没有返回任何值。然后我使用 async-await 解决了它,但我不明白为什么?
async function asyncFunction(input) {
try {
let output = await Promise.resolve("output");
return output;
} catch (err) {
console.log(err);
}
}
function promiseFunction(input) {
Promise.resolve().then(function() {
return "output";
}).catch(function(err){
console.log(err);
})
}
async function run() {
let a = await asyncFunction();
let b = await promiseFunction();
console.log("async function output: " + a); //async function output: output
console.log("promise function output: " + b); //promise function output: undefined
}
run();
我希望 asyncFunction() 和 promiseFunction() 都返回值“output”,但 promiseFunction 返回的是 undefined。
最佳答案
async
函数总是返回 promise 。如果您在普通函数中省略 return 语句,例如:
function doSomething(x) {
x.y = 2;
}
然后返回undefined。
doSomething({}) === undefined // true
如果在 async
函数中省略 return 语句
async function doSomething(x) {
x.y = 2;
}
它返回一个未定义的 promise
doSomething({}).then(result => result === undefined); // resolves to be true
在您的非 async
函数中,您不会返回任何内容。您需要返回
Promise.resolve().then(...)
行。这是使用 async/await
语法的好处之一。无需担心正确链接您的 promise 和返回。只做你的工作,在需要的地方等待
,然后返回
值。
关于javascript - 为什么 async await 函数返回一个值,而 promise 函数返回一个未定义的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58158075/