admin管理员组文章数量:1181432
I want to write an application that requests a token from an API. As long as this token isn't available I don't want to continue with the rest of the application. So it has to be like a synchronous HTTP request.
My goal is to create a function that does the request and then returns the token like:
var token=getToken(); //After this function has finished
makeRequest(token); //I want this function to be executed
How can I do this?
I want to write an application that requests a token from an API. As long as this token isn't available I don't want to continue with the rest of the application. So it has to be like a synchronous HTTP request.
My goal is to create a function that does the request and then returns the token like:
var token=getToken(); //After this function has finished
makeRequest(token); //I want this function to be executed
How can I do this?
Share Improve this question asked Mar 9, 2017 at 17:10 ApatusApatus 1671 gold badge2 silver badges10 bronze badges 1- Related: stackoverflow.com/questions/6048504/… – Ciro Santilli OurBigBook.com Commented Dec 25, 2021 at 11:04
4 Answers
Reset to default 18It doesn't want to be synchronous at all. Embrace the power of callbacks:
function getToken(callback) {
//get the token here
callback(token);
};
getToken(function(token){
makeRequest(token);
});
That ensures makeRequest isn't executed until after getToken is completed.
My goal is to create a function that does the request and then returns the token
You cannot make a function that returns a value that it doesn't have immediately. You can only return a promise.
Then in some other part of code you can either wait for the promise to be fulfilled by using the then handler, or you can use something like:
var token = await getToken();
inside of an async function to wait for that value to be available, but only if the getToken()
function returns a promise.
For example, using the request-promise
module it would be something like:
var rp = require('request-promise');
function getToken() {
// this returns a promise:
return rp('http://www.example.com/some/path');
})
And then some other function:
function otherFunction() {
getToken().then(token => {
// you have your token here
}).catch(err => {
// you have some error
});
}
Or, with async function
something like this:
async function someFunction() {
try {
var token = await getToken();
// you have your token here
} catch (err) {
// you have some error
}
}
See: https://www.npmjs.com/package/request-promise
Note that async function
and await
is define in ECMAScript 2017 Draft (ECMA-262) which is not final yet at the time of this writing as of March 2017 (it will be in June 2017).
But it's already available in Node since v7.6 (and it was available since v7.0 if you used the --harmony
flag). For the compatibility with Node versions, see:
- http://node.green/#ES2017-features-async-functions
If you want similar features for older Node versions with slightly different syntax, you can use modules like co or Promise.coroutine from Bluebird.
You can use javascript Promise or promise library like async
By javaScript promise:
new Promise((resolve, reject) => {
resolve(getToken());
}).then(token =>{
//do you rest of the work
makeRequest(token);
}).catch(err =>{
console.error(err)
})
You can use the feature of ES6 called generator. You may follow this article for deeper concepts. But basically you can use generators and promises to get this job done. I'm using bluebird to promisify and manage the generator.
Your code should be fine like the example below.
const Promise = require('bluebird');
function getToken(){
return new Promise(resolve=>{
//Do request do get the token, then call resolve(token).
})
}
function makeRequest(token){
return new Promise(resolve=>{
//Do request do get whatever you whant passing the token, then call resolve(result).
})
}
function* doAsyncLikeSync(){
const token= yield getToken(); //After this function has finished
const result = yield makeRequest(token); //I want this function to be executed
return result;
}
Promise.coroutine(doAsyncLikeSync)()
.then(result => {
//Do something with the result
})
本文标签: javascriptNodeJS wait for HTTP requestStack Overflow
版权声明:本文标题:javascript - NodeJS wait for HTTP request - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738226344a2070248.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论