gpt4 book ai didi

javascript - 如何从 Node 中的函数返回数据?

转载 作者:太空宇宙 更新时间:2023-11-04 00:50:28 25 4
gpt4 key购买 nike

我正在使用 Express 并尝试自学 Node/javascript 回调,但我偶然发现了一些东西。

我有一条如下所示的路线:

var express = require('express');
var router = express.Router();
var api = require('../api');

router.get('/',function(req, res, next){
var modulename = api.modulename;
modulename.methodname(res);
});

module.exports = router;

然后上面调用的模块如下所示:

var library = require('library');
var instances = {};
var modulename = {

getAllInstances: function(res) {
var request = new library.asyncMethod();
request.on('success', function(resp) {
instances = resp.data;
res.setHeader("Content-Type","application/json");
var returnInstances = {
id: instances[0].InstanceId,
state: {name: instances[0].State.Name, code: instances[0].State.Code}
};
res.send(returnInstances);
})
.on('error', function(resp){
console.log(resp);
})
}
};

module.exports = modulename;

如您所见,我正在将响应参数传递到我的模块,但我宁愿传回实例,然后在路由中返回api.modulename.instances,像这样:

var library = require('library');
var instances = {};
var modulename = {

getAllInstances: function() {
var request = new library.asyncMethod();
request.on('success', function(resp) {
var returnData = resp.data;
instances = {
id: returnData[0].InstanceId,
state: {name: returnData[0].State.Name, code: returnData[0].State.Code}
};
})
.on('error', function(resp){
console.log(resp);
})
.send();
}
};

module.exports = modulename;

但是,当我这样做时,它会作为默认值 {} 出现,但如果我按照上面的方式运行它,我会得到输出,所以我知道其中应该有数据。

最佳答案

如果我误解了您的问题,请告诉我。如果您说要从 getAllInstances 传回对象,那么您可以传入一个回调并从事件处理程序中调用它,如下所示 -

router.get('/',function(req, res, next){
var modulename = api.modulename;
modulename.getAllInstances(res, function(err, instances){
if(err){ ... }
else{
res.send(instances); //or however you want to use instances
}
});
});

getInstances

var modulename = {
getAllInstances: function(res, cb) {
var request = new library.asyncMethod();
request.on('success', function(resp) {
instances = resp.data;

var returnInstances = {
id: instances[0].InstanceId,
state: {name: instances[0].State.Name, code: instances[0].State.Code}
};
cb(null, instances);
})
.on('error', function(err){
cb(err, null));
});
//.send(); not sure what this is it seems to be request.send() ??
}
};

关于javascript - 如何从 Node 中的函数返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32756776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com