I want a common function like this
function getSrc() {
var src = axios.get('assist/img/src')
.then(function (response) {
return response.data; // the response.data is string of src
})
.catch(function (response) {
console.log(response);
});
// doing other something
return src;
}
but I can't got right value, and I know this is wrong way.
How to do can implement it like this ?
Something need to be supplement.
The reason why I want this is that I don't want function's change affect where call it.
For example, I use jQuery's ajax instead of axios to get something of Server, maybe would be trouble.
Chuoke ChungYoung
PHPer
Chuoke ChungYoung since axios returns a promise object, return the axios.get() promise instead of passing the data to src variable, and then do your magic to the data outside.
here is an example
function getSrc() {
return axios.get('assist/img/src');
}
getSrc.then(function (response) {
return response.data; // now the data is accessable from here.
}).catch(function (response) {
console.log(response);
});
I'm not sure I understand what exactly you want. Axios.get() returns a promise, it is async ofcourse. That means your getSrc() is also async so it cannot just return a value when called. That value does not exist yet at the moment of calling it!
So, your code looks ok, your getSrc() will return a promise which you can manipulate later. Only the line ''// doing other something" seems wrong. That's going to execute in parallel with axios.get()! Depeding on what that other something is, you might want to put it in another .then().
Can you give us an example of what exactly you expect your getSrc() to return?
Cipto Hadi
Alok Deshwal
Node.js Developer | AWS guru
Solution 1: You can use callback function as parameter here, just pass callback function to getSrc() Method and call getSrc() function using the same callback function.
Solution 2: Another solution is you can take advantage of async/await feature of ES 7(ES 2016) just make this function async and put await keyword just before calling your axios.METHOD.