如何从Node.js中的嵌套函数返回? [英] How to return from nested function in Node.js?
问题描述
我将dynamoDB函数包装到另一个函数中,并且在将其返回到"item"常量时遇到问题.我在这里想念的是什么?
I'm wrapping my dynamoDB function into another function and I'm having issues with returning it to the "item" const. What I'm missing here?
作品:
const params = {
TableName: table,
Key: {
id: id
},
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
callback(null, {
statusCode: error.statusCode || 501,
body: 'Couldn\'t fetch the item.',
});
return;
}
const item = result.Item
})
不起作用(返回未定义):
Doesn't work (returns undefinied):
const getFromDb = () => {
const params = {
TableName: table,
Key: {
id: id
},
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
callback(null, {
statusCode: error.statusCode || 501,
body: 'Couldn\'t fetch the item.',
});
return;
}
return result.Item
})
}
// Get from db
const item = getFromDb()
// do stuff with result item...
推荐答案
您的代码中当前发生的是 getFromDb
函数将运行 dynamoDb.get(...)
并立即返回(在您的情况下未定义,因为 getFromDb
中没有return语句).到 getFromDb
返回时,您的dynamoDb请求甚至尚未解决,它将在将来的某个时间解决,并调用您提供的回调(错误,结果)=>{...}
What currently happens in your code is getFromDb
function will run dynamoDb.get(...)
and immediately return (undefined in your case, because there is no return statement inside getFromDb
). By the time getFromDb
returns, your dynamoDb request hasn't even resolved yet, it will resolve at some point in the future and call the callback you provided (error, result) => { ... }
要实现您所描述的内容,您需要:
To achieve what you described, you need to:
- 使
getFromDb
返回承诺,仅在您的请求解决后才能解决 调用该函数时, -
等待
,以获取Promise解析为结果的结果(如果拒绝则返回错误)
- make
getFromDb
return Promise which will only resolve after your request resolves await
for that function when calling it, getting result into which your Promise resolves (or and error if it rejects)
.
// marking this function async is not required but good to have
// to not forget that this function returns a promise, not immediate result
const getFromDb = async () => {
// wrapped body in a promise
return new Promise((resolve, reject) => {
const params = {
TableName: table,
Key: {
id: id
},
}
dynamoDb.get(params, (error, result) => {
if (error) {
// in case of error, we reject promise with that error
reject(error)
return
}
// otherwise, we resolve with result
resolve(result.Item)
})
})
}
// usage with async/await
// I wrapped significant code in asynchronous function f and then called it
// just to emphasize that you can only use async/await inside async function
// if you are already in async function, you don't need to do this
const f = async () => {
try {
const item = await getFromDb();
console.log(item)
} catch(error) {
// the error we rejected with
console.error(error)
}
}
f()
// alternative way without async/await, using Promise chaining
getFromDb()
.then(item => console.log(item))
.catch(error => console.error(error))
这篇关于如何从Node.js中的嵌套函数返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!