0

I'm a bit new to javascript and the whole async-think ...

I'm trying to retrieve data from one of two datasources and then process it. The problem is that the script continues on (trying to process the data) before the results of the fetch(s) have returned.

fetch source#1

if not successful ... fetch source#2

process the data

I've tried everything that I can think of to slow the process down. Basically, the script initiates the 1st fetch then proceeds to process the data before the results have been returned.

Here's the main block

getData(someid)
.then((response) => {
    resText = response;
})
.catch((error) => {
    console.log('error: ' + error)
});

if (resText === "") {
    getData2(someid)
    .then((response) => {
        resText = response;
    })
    .catch((error) => {
        console.log('error: ' + error)
    });
}
// process the data
console.log('resText= ' + resText)

Here's the fetch code:

async function getData(someid) {
    var url = 'https://www.somesite.com/get someid';
    let res = await fetch(url);
    if (res.status == 200) {
        let respText = await res.text();
        return respText;
    }
    throw new Error(res.status);
}

I can't imagine that I am the first person to encounter this, so there must be a solution. Am I not using the environment properly? Is there a way to treat the fetches as events and wait for them to complete before proceeding on to the next step?

Thanks in advance for your help!

ChinaBOb
  • 11
  • 1

0 Answers0