我正在使用aws-lib npm包调用Amazon产品API。我试图获得该调用的结果,然后将该信息保存到我的数据库中,我遇到的问题是,当我尝试将调用的结果设置为调用时,如果我使用大量参数进行调用我得到的产品未定义,因为API调用尚未完全返回。我尝试使用回调和承诺,以确保在我做任何其他事情之前完全返回API结果,但我无法让它工作。
这是我的代码的当前状态
var aws = require('aws-lib');
var host = "http://webservices.amazon.co.uk/onca/xml"
var prodAdvOptions = {
host: "webservices.amazon.co.uk",
region: "UK"
};
// provide credentials
var prodAdv = aws.createProdAdvClient(myKey, myPass, myId, prodAdvOptions);
.post(function(req, res) {
// Options for the Amazon API
var options = {
ItemId: req.body.itemId,
ResponseGroup: "OfferFull, ItemAttributes",
Condition: "New",
MerchantId: "Amazon"
}
getInfo(options, saveProduct, res);
}
function getInfo(options, saveProduct, res){
// Make call to the API
prodAdv.call("ItemLookup", options, function(err, result) {
//create new product
var product = new Product();
product.name = result.name
//assign lots more things to the product - these will return undefined which is the problem
saveProduct(product);
})
};
function saveProduct(product){
// save product to the database
};
这是使用aws-lib
调用APIexports.init = init;
function init(genericAWSClient) {
return createProdAdvClient;
function createProdAdvClient(accessKeyId, secretAccessKey, associateTag, options) {
options = options || {};
var client = genericAWSClient({
host: options.host || "ecs.amazonaws.com",
path: options.path || "/onca/xml",
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
secure: options.secure
});
return {
client: client,
call: call
};
function call(action, query, callback) {
query["Operation"] = action
query["Service"] = "AWSECommerceService"
query["Version"] = options.version || '2009-10-01'
query["AssociateTag"] = associateTag;
query["Region"] = options.region || "US"
return client.call(action, query, callback);
}
}
}
我认为我没有正确使用回调,或者需要另外一个将结果分配给产品,但无法解决我出错的地方。
感谢您的帮助,我已经对这个问题持续了2天。
答案 0 :(得分:1)
可能更容易看到最初没有承诺的情况,然后在达成谅解后使用承诺。
该计划流程的一个选项是:
post
回调getInfo
被称为prodAdv
被调用,它是ansynchronous,这意味着必须在调用aws完成后提供回调函数。saveProduct
,另一个异步函数。 saveProduct
必须注册回调,以便在完成对数据库的调用后执行某些操作。res.send
api.post('somePost', function(req, resp) {
makeAWSCallAsync(params, function(err, awsRespProducts) {
saveProductsAsync(awsRespProducts, function(err, dbResp) {
// db call has been completed
resp.send();
});
});
});
这是非常简单的骨头,一路上可能会检查错误。一旦这个工作,你可以重构使用promises,这将删除嵌套的回调。