我有这个Node.js片段。
var requestify = require('requestify');
// [...]
function remoterequest(url, data) {
requestify.post(url, data).then(function(response) {
var res = response.getBody();
// TODO use res to send back to the client the number of expected outputs
});
return true;
}我需要将res内容而不是true返回给调用者。
我怎么能这么做?在这种情况下,requestify的方法是异步的,因此无法检索返回的值(因为它尚未生成)。如何解决它?我如何发送同步HTTP请求(即使没有requestify)?
发布于 2018-04-27 12:12:58
您需要返回一个承诺,并在remoteRequest返回的承诺的方法中使用它:
var requestify = require('requestify');
// [...]
function remoterequest(url, data) {
return requestify
.post(url, data)
.then((response) => response.getBody());
}
//....
remoteRequest('/foo', {bar: 'baz'}).then(res => {
//Do something with res...
});请注意,它仍然不是一个同步发布,但如果这是您想要的,则可以在可用时使用response.getBody()。
发布于 2018-04-27 12:48:43
您可以参考关于如何使用承诺How do I return the response from an asynchronous call?返回的内容的讨论。
正如@Logar所提到的,您不能直接使用承诺中返回的内容。必须首先调用返回承诺的方法,并使用.then使返回的内容可用。
示例
var requestify = require('requestify');
// [...]
// This function returns a promise, so you have to call it followed by `.then` to be able to use its returned content
function remoterequest(url, data) {
requestify
.post(url, data)
.then((response) => {
return response.getBody();
});
}
//....
//... Some other code here
//....
// Make a call to your function returning the promise
remoterequest('your-url-here', {data-to-pass-as-param})
.then((res) => { // Calling `.then` here to access the returned content from `remoterequest` function
// Now you can use `res` content here
});
https://stackoverflow.com/questions/50061810
复制相似问题