[英]AWS Lambda nodejs - problem with return values from await async function
这是 AWS Lambda function 等待异步 function。 我无法获得返回值。 只要服务器上仍有一些要检索的值,我就需要循环获取数据:
let do_search = true;
while (do_search) {
const url = 'xxx';
await fetchData(url)
.then(response => {
console.log("fetchData result:", response);
if (response) {
console.log("Stop searching, no more data");
do_search = false;
}
})
.....
而当还有更多数据要处理时,我的 fetchData 返回 false 值。 fetchData function:
async function fetchData(url) {
...
console.log("Returning false");
return false;
问题是我的 fetchData 甚至返回 false,我的日志总是:
Returning false
fetchData result: true
我还尝试使用其他方法:
const createModelBInstance = async () => {
let response = await fetchData(url)
console.log("fetchData result:", response);
if (response){
do_search=false;
}
}
await createModelBInstance();
基于这个论坛上的一些例子。 但完全相同的问题,我的 fetchData 返回 false 而“fetchData 结果:true”。
任何工作示例? 返回的 Promise 值导致简单的代码非常复杂:(
您不应该在 JavaScript 中编写硬循环。 它是单线程的。
这是一个 fetchData 方法的示例,它休眠 1 秒,然后指示数据是否可用(可用的可能性为 10%,不可用的可能性为 90%)。 这纯粹是为了模拟您的异步 URL 提取器。
const getRandom = (low, count) => {
return Math.floor((Math.random() * count) + low)
}
const fetchData = () => {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const rand = getRandom(1, 10);
if (rand % 7) {
resolve({ rand });
} else {
resolve({ data: 'Here is the data', rand });
}
}, 1000);
});
return promise;
}
这是每隔 2 秒调用此代码的示例,直到数据可用。
const interval = setInterval(() => {
fetchData().then(rc => {
console.log(rc);
if (rc.data) {
// do something with rc.data
clearInterval(interval);
}
});
}, 2000);
output 的示例:
{ rand: 2 }
{ rand: 10 }
{ rand: 1 }
{ data: 'Here is the data', rand: 7 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.