0

I'm using the libraby request for my ajax call, this library give me a response and after I'm using JSON.

I've got a constant id inside and where I'm block is to use this constant outside the request()

I know that I need a promises but I don't understand how to use it ...

const options = {
***
 },
};

request(options, function(error, response, issue) {
 const json = JSON.parse(issue);
 for (let i = 0; i < json.versions.length; i++) {
    const test = json.versions[i].name;
    if (test === version) {
        const id = json.versions[i].id;  //here id
    }
 }
});
console.log(id); // I need to retrieve the const id here but id it's undefined, so how can I specified id 
  • I would move away from the request library as it was deprecated. I would advise looking into axios or using native fetch. here is some documentation on fetch which is really easy to use. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – jgetner Apr 10 '20 at 07:10
  • I see but if I use their new method call, would I have the same problem ? @jgetner – fzefzef zefzef Apr 10 '20 at 07:12
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ADyson Apr 10 '20 at 07:30
  • I see this issue but don't understand how use promises .. @ADyson – fzefzef zefzef Apr 10 '20 at 07:33
  • Then you need to find some tutorials and examples which can teach you – ADyson Apr 10 '20 at 07:34
  • Can you explain a little bit for my example ? @ADyson – fzefzef zefzef Apr 10 '20 at 07:37
  • Read the answers in the link I posted. There are many many examples there already. And hundreds of others online too. The same principles apply in all cases. I agree you should use a different Ajax library. The fetch() method is the obvious choice. After that your options for getting the result are 1) use a callback, 2) use Promises (which effectively involves a structured version of using callbacks as well, 3) use async/await. All of these are well documented online. – ADyson Apr 10 '20 at 07:47

3 Answers3

2

Try using:

const options = {
***
 },
};
let id;

function getMyBody(options, callback) {
  request(options, function(error, response, issue) {
 const json = JSON.parse(issue);
 for (let i = 0; i < json.versions.length; i++) {
    const test = json.versions[i].name;
    if (test === version) {
        const id = json.versions[i].id;  //here id
        callback(id);
    }
 }
});  
  });
}
getMyBody(options,(id)=>{this.id = id; console.log(id);})
AyushKatiyar
  • 1,000
  • 8
  • 15
0

Use callback function

let id = 0;

fetchData = () => {
  console.log(`id before ${id}`)


  fetch('api', { method: 'GET', 
        headers: { 'Authorization': ** }  })
     .then((res) {
       onCompleted(res)
     }):;

}

onCompleted = (data) => {
  id = data;
  console.log(`id after ${id}`)
}

fetchData();
naijab.com
  • 508
  • 6
  • 10
-2

Simply create a variable outside the callback and assign it inside the callback result

var id 

const options = {
***
 },
};

request(options, function(error, response, issue) {
 const json = JSON.parse(issue);
 for (let i = 0; i < json.versions.length; i++) {
    const test = json.versions[i].name;
    if (test === version) {
        id = json.versions[i].id;  // here id is the id we declared in line 1.
    }
 }
});
console.log(id); 

The value of id is going to be undefined at console.log(id); because the http request has not yet executed completely. You can either use callbacks, or a promise or a setInterval for id to be defined.

Using setInterval

var id 

const options = {
***
 },
};

request(options, function(error, response, issue) {
 const json = JSON.parse(issue);
 for (let i = 0; i < json.versions.length; i++) {
    const test = json.versions[i].name;
    if (test === version) {
        id = json.versions[i].id;  // here id is the id we declared in line 1.
    }
 }
});

var _interval = setInterval(() => {
    if(id !== undefined) {
        console.log(id); 
        // clearing interval
        clearInterval(_interval)
    }
}, 1000)

Using promise

below is an example of how to convert your request into a promise and then use the id

const options = {};

const promised_request = () => new Promise((resolve, reject) => {
  request(options, function (error, response, issue) {
    if (error) {
      return reject(error);
    }

    const json = JSON.parse(issue);
    for (let i = 0; i < json.versions.length; i++) {
      const test = json.versions[i].name;
      if (test === version) {
        const id = json.versions[i].id;
        return resolve(id);
      }
    }
  });
});

promised_request().then((id) => {
  // use your id here
  console.log(id);
});

Yousuf Khan
  • 334
  • 3
  • 12
  • The solution is not valid as the ```request``` method is async call so when javascript engine reaches ```console.log(id); ``` the id is still not set Hence the result is still undefined. – AyushKatiyar Apr 10 '20 at 07:31
  • I've got undefined – fzefzef zefzef Apr 10 '20 at 07:31
  • yes well it'll definetly be undefined because the value of Id is not defined yet. You'll have to wait in a timeout for id To be defined. – Yousuf Khan Apr 10 '20 at 07:42
  • @YousufKhan Timeout is a terrible idea, you can't guarantee the async call will definitely be complete when the timer expires. I think you need to read about Promises and async/await as well as OP – ADyson Apr 10 '20 at 07:44
  • well I can use Promises but they were too complicated for the OP `I don't understand how to use it`, so an interval will be a better and naive solution – Yousuf Khan Apr 10 '20 at 07:47
  • A naive solution which contains known flaws is never a better solution. Promises are not _that_ hard to learn, OP will get it if they spend a little time on the topic. And then they can write code which will work reliably, which will be better for everyone. A lot of people struggle with the concept initially - I certainly did. But once you use it a few times and find some good examples, you get the hang of it. – ADyson Apr 10 '20 at 08:33