-1

I have the below code which call api and get status using node-fetch . I need to use node-fetch 2.6.1 and use the code like .then-->.then cannot able to use async await .

function fetching(){
 fetch(jobsurl, requestOptions)
    .then(response => response.text())
    .then(result => {
        
        console.log("------------the job id is ------------"); 
        console.log(eval(result)[0]["id"])
        console.log("\n\n\n\n\n")
        console.log("--------------The Job Status is------------");
        console.log(eval(result)[0]["status"])
        console.log("\n\n\n\n\n")
        var job_id=eval(result)[0]["id"].toString();
        var stat=eval(result)[0]["status"];

       while(stat != "success"){
           
         fetch(jobsurl, requestOptions)
           .then(response => response.text())
           .then(result => {
               console.log("------------the job id is ------------"); 
               console.log(eval(result)[0]["id"])
               console.log("\n\n\n\n\n")
               console.log("--------------The Job Status is------------");
               console.log(eval(result)[0]["status"])
               console.log("\n\n\n\n\n")
               job_id=eval(result)[0]["id"].toString();
               stat=eval(result)[0]["status"];
            }
           // as it is success so call the main url
           fetch()....             

           }//ftehcing end

now it has stat variable inside then that give the job status success or pending if it sucess then only I can proceed. But for that I need to iterate and check when it will get success every time. so I used while loop.

But it is not working. as stat value check every time by calling fetch inside it.

Please suggest

Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74
  • 1
    What do you mean "cannot able to use async await"? If you can use `.then()`, you can use `async` and `await` just fine. – AKX Apr 19 '22 at 06:55
  • because it should under a sync method – Rajarshi Das Apr 19 '22 at 07:09
  • `async` functions return promises, so if you have a non-async function you can't convert to async, you can use `.then()` there. – AKX Apr 19 '22 at 07:10
  • 1
    If you're calling `fetch()` your function is already asynchronous, whether it's tagged as `async` (so you can use `await`) or not. It appears you have some basic misunderstanding of asynchronous code in nodejs. Making it `async` and using `await` will sacrifice nothing and make your function easier to program as the solution AKX shows you illustrates. There is NO reason not to do it that way. – jfriend00 Apr 19 '22 at 07:15

1 Answers1

1

Here's an async/await reworking of your code that makes the loop pretty much trivial.

There's also

  • proper error handling (using response.ok)
  • no use of evalresponse.json() should do what you want
  • a delay between requests (so as not to spam the server milliseconds apart)
function delay(number) {
  return new Promise(resolve => setTimeout(resolve, number));
}

async function fetching() {
  while (true) {
    const response = await fetch(jobsurl, requestOptions);
    if (!response.ok) {
      throw new Error(`HTTP error, status = ${response.status}`);
    }
    const results = await response.json();
    const {id, status} = results[0];
    console.log(`Job ${id} status: ${status}`);
    if (status === 'success') {
      break;
    }
    await delay(500);  // Wait for a bit before re-requesting
  }
  // Call main url..?
}

EDIT: If you absolutely can't use async/await, you'd need to use a recursive function, something like this, and it's pretty hard to read.

function delay(number) {
  return new Promise((resolve) => setTimeout(resolve, number));
}

function fetching() {
  function _recursive() {
    return fetch(jobsurl, requestOptions)
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error, status = ${response.status}`);
        }
        return response.json();
      })
      .then(results => {
        const {id, status} = results[0];
        console.log(`Job ${id} status: ${status}`);
        if (status === 'success') {
          return results;
        }
        return delay(500).then(_recursive);
      });
  }
  return _recursive();
}

function main() {
  fetching().then(results => {
    console.log(results);
    // call main URL..?
  });
}
AKX
  • 152,115
  • 15
  • 115
  • 172
  • we cannot call async function fetchJobstaff it should be a sync function platform where it is executing not support this – Rajarshi Das Apr 19 '22 at 07:10
  • If you use `fetch()`, you're already not synchronous. – AKX Apr 19 '22 at 07:11
  • but my method is function fetching() not asyn function fetch..() – Rajarshi Das Apr 19 '22 at 07:12
  • You're using `node-fetch`, which is always asynchronous. – AKX Apr 19 '22 at 07:12
  • we cannot use ` const jj = await fetchJobStuff()` – Rajarshi Das Apr 19 '22 at 07:13
  • 1
    Why not? Where are you running this? You've tagged this as `node.js`, which most assuredly can do `await`. – AKX Apr 19 '22 at 07:14
  • Actually it is using a platform which is not supported outside declaration like above we need to define a sync method and use fetch or any async inside it and then call the method outside like `fetching()` – Rajarshi Das Apr 19 '22 at 07:19
  • What platform is it, _please_? In any case, `async function ...` is just syntactic sugar for making a function return a promise. If this platform doesn't support the `async function` syntax at all, you could transpile your code to plain `function`s first. – AKX Apr 19 '22 at 07:22
  • In any case, I added a non-async recursive reformulation. – AKX Apr 19 '22 at 07:45