【问题标题】:How to get response out the function to return through functions in Node.js如何从函数中获取响应以通过 Node.js 中的函数返回
【发布时间】:2021-07-24 14:33:40
【问题描述】:
function api(method, body){
console.log(body)
unirest.post(BASE_URL + method)
.send(body)
.end(function (response) {
return response.body
});
}
这个 api 函数没有返回我提到的内容
我能做什么
【问题讨论】:
标签:
node.js
http
httprequest
【解决方案1】:
原因:post 是一个异步调用,当它从请求中接收到数据时,该函数已经执行并且不返回任何内容。你可以使用 Promise 来获取结果,你可以这样实现:
function api(method,body){
return new Promise((resolve, reject) => {
console.log(body)
unirest.post(BASE_URL + method)
.send(body)
.end(function (response) {
resolve(response.body);
});
//if there is any error you can call reject
// reject('You error message');
})
}
//to get the value you can use then/catch or async/await
api().then((data) => {console.log(`Data is ${data}`)})
.catch(console.log);
有关承诺的更多详细信息,请查看here。
【解决方案2】:
您在异步回调中使用return。
这个会起作用,但你必须使用await或.then
function api(method,body){
let ret = new Promise((resolve, reject) => {
console.log(body)
unirest.post(BASE_URL + method)
.send(body)
.end(function (response) {
resolve(response.body)
});
return ret
}