我有两个.js文件,例如:
index.js:
app.get("/testing",(req,res) => {
testAsyncFunction().then((resolvedData) => {
res.send(resolvedData);
});
})
和server.js:
const asyncFunction = () => {
return new Promise((res) => {
setTimeout(() => {
res('resolved');
},3000 )
})
}
const testAsyncFunction = () => {
return new Promise(async (res) => {
const result = await asyncFunction();
return res(result);
})
}
这可以按预期工作,但是如果我将testAsyncFunction(这样我就不会创建新的Promise)更改为这样的话:
const testAsyncFunction = async () => {
const result = await asyncFunction();
return result;
}
以及在index.js中:
app.get("/testing",res) => {
res.send(testAsyncFunction());
})
我得到一个空对象,因为它没有等待3秒,在后一种情况下我会丢失什么?我要避免创建新的Promise只是为了等待另一个诺言。
更新
我将testAsyncFunction更改为以下内容:
const testAsyncFunction = () => {
asyncFunction().then((result) => {
return result;
})
}
即使具有上述功能。不是一个异步函数,为什么我仍然需要在index.js
中等待它。我假设在这种情况下返回的值将不是一个保证,所以这就是我感到困惑的部分。