This is AWS Lambda function awaiting on async function. I can not get returned value. I need to do fetch data in loop as long as there are still some values on the server to be retrieved:
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;
}
})
.....
while my fetchData returns false value when there is still more data to be processed. fetchData function:
async function fetchData(url) {
...
console.log("Returning false");
return false;
The problem is even my fetchData returns false, my log are always:
Returning false
fetchData result: true
I have also tried to use other approach with:
const createModelBInstance = async () => {
let response = await fetchData(url)
console.log("fetchData result:", response);
if (response){
do_search=false;
}
}
await createModelBInstance();
Based on some examples on this forum. But exactly same problem, my fetchData returns false while "fetchData result: true".
Any working example? That Promise values returned are causing simple code to be very complicated:(
You shouldn't write hard loops in JavaScript. It's single-threaded.
Here's an example of a fetchData method that sleeps for 1 second, then indicates whether or not data is available (available with 10% likelihood, not available 90% likelihood). This is purely to simulate your asynchronous URL fetcher.
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;
}
Here's an example of calling this code on an interval, every 2 seconds, until data becomes available.
const interval = setInterval(() => {
fetchData().then(rc => {
console.log(rc);
if (rc.data) {
// do something with rc.data
clearInterval(interval);
}
});
}, 2000);
An example of the output:
{ rand: 2 }
{ rand: 10 }
{ rand: 1 }
{ data: 'Here is the data', rand: 7 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.