gpt4 book ai didi

javascript - 将数据从服务传递到 Controller

转载 作者:行者123 更新时间:2023-12-03 07:53:51 24 4
gpt4 key购买 nike

我创建了一个旨在访问 API 的服务。我需要将数据返回到我的 Controller ,但由于我对 sails 完全陌生,所以不确定如何执行此操作。

我的服务:

// API call to get the ID of contact within Get Response with email address
getContact: function(options) {

// establish connection to API
var api = new getResponse(apiKey, apiUrl);

var contact = api.getContactsByEmail(options.email, null, null, function (response) {
JSON.stringify(response);
console.log(JSON.stringify(response));
});

return contact;

},

我知道 API 调用正在工作,因为当我记录响应时,我得到了正确的响应:

{"success":true,"data":{"error":null,"id":1,"result":{"sds":{"ip":null,"name":"全名","origin":"api","cycle_day":0,"email":"email@email.com","campaign":"id","created_on":"date","changed_on":null} }}}

我的 Controller :

index: function(req, res) {

var contact = GetresponseService.getContact({email: 'email@email.com'});

console.log(contact);
return res.send(contact);

}

我想检索 ID 值,但是当我记录联系人的值时,我得到了未定义的信息。我认为我的问题与范围有关,但不确定。

有人能指出我正确的方向吗?

最佳答案

因为您直接从 api.getContactsByEmail() 赋值它不返回值。

根据 Node.js 的本质,函数 api.getContactsByEmail()为您提供回调 response 。您必须从匿名回调函数中获取值,如下所示:

// API call to get the ID of contact within Get Response with email address
getContact: function(options) {

// establish connection to API
var api = new getResponse(apiKey, apiUrl);
var contact = "";
api.getContactsByEmail(options.email, null, null, function (response) {

contact = response;

JSON.stringify(response);
console.log(JSON.stringify(response));

return contact;
});

}

更多...

我认为,返回回调比直接返回值更好。

// API call to get the ID of contact within Get Response with email address
getContact: function(options, callback) {

// establish connection to API
var api = new getResponse(apiKey, apiUrl);
var contact = "";
api.getContactsByEmail(options.email, null, null, function (response) {

contact = response;

JSON.stringify(response);
console.log(JSON.stringify(response));

if(typeof(callback) == "function")
callback(contact);
else
return contact; // return contact if there is callback func.
});

}

您可以像这样使用它:

index: function(req, res) {

var contact;
GetresponseService.getContact({email: 'email@email.com'}, function(contactResult) {

contact = contactResult;
console.log(contact);
return res.send(contact);
});


}

关于javascript - 将数据从服务传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883624/

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