Javascript 如何在nodejs路由器中使用承诺和收益?
我尝试配置后端工厂以使用Amazon产品Api获取数据 以下是我在nodejs中执行的脚本:Javascript 如何在nodejs路由器中使用承诺和收益?,javascript,node.js,amazon-web-services,Javascript,Node.js,Amazon Web Services,我尝试配置后端工厂以使用Amazon产品Api获取数据 以下是我在nodejs中执行的脚本: var amazon = require('amazon-product-api'); var client = amazon.createClient({ awsId: 'ID', awsSecret: 'sectret', awsTag: 'tag', }); // SERVER // var Promise = require('bluebird'); var koa =
var amazon = require('amazon-product-api');
var client = amazon.createClient({
awsId: 'ID',
awsSecret: 'sectret',
awsTag: 'tag',
});
// SERVER
// var Promise = require('bluebird');
var koa = require('koa');
var router = require('koa-router')();
router.get('/node/:index', function* () {
this.body = yield client.browseNodeLookup({
browseNodeId: this.params.index,
});
});
router.get('/', function* (ctx, next) {
var node = yield client.browseNodeLookup({
browseNodeId: 1063498,
});
this.body = node;
});
var app = koa();
app.use(router.routes()).use(router.allowedMethods());
app.listen(8005);
在前端,我使用bluebird.js提供的Promise.map()来映射amazon的一系列产品节点。在函数的最后,我希望将数组中的链接(字符串)转换为对象(通过API获得)。
以下是函数:
someFn(links) { // links is an array of node IDs
return Promise.map(links, (link) => {
var link = link;
if (typeof link === "object" || level > 1) {
return link;
} else {
return loadUrl({
url: 'http://localhost:8005/node/'+link,
action: 'json',
}).then((res) => {
if (isJSON(res)) {
return new Category(res); // transform string to object
} else {
return link;
}
});
}
});
}
Amazon最多允许10次查询,这就是为什么我需要运行函数几次或循环它以获取数组中每个字符串的对象
想法是在后端等待成功的答案,或者重复查询(yield client.browseNodeLookup)
或者只需传递节点ID数组,并获取每个节点ID的JSON作为结果
我对nodejs服务器和路由配置没有太多经验,因此您能帮助我正确配置它吗?我仍然没有找到使用后端执行任务的解决方案,但我已经更新了loadUrl函数。函数会自动运行,直到检索到成功的答案:
function loadUrl(options) {
var options = options;
return new Promise((resolve, reject) => {
$.post('/', options).done((result) => {
if (result != 'Internal Server Error') {
resolve(result);
} else {
(function run(x) {
var x = x || 0;
// 300 - calls limit
// for me 100 is enough
if (x <= 300) {
setTimeout(function() {
$.post('/', options).done((result) => {
if (result != 'Internal Server Error') {
resolve(result);
} else {
console.log('call', x);
run(x+1);
}
});
}, 100);
} else {
resolve(result);
}
})();
}
});
});
}
函数加载URL(选项){
var期权=期权;
返回新承诺((解决、拒绝)=>{
$.post('/',options).done((结果)=>{
如果(结果!=“内部服务器错误”){
决心(结果);
}否则{
(功能运行(x){
var x=x | | 0;
//300-通话限制
//对我来说100英镑就够了
if(x){
如果(结果!=“内部服务器错误”){
决心(结果);
}否则{
console.log('call',x);
运行(x+1);
}
});
}, 100);
}否则{
决心(结果);
}
})();
}
});
});
}
据我所知,$.post()的答案有时间限制,这就是我遇到问题的原因。数据是由后端工厂获得的,但我的前端脚本没有准备好等待它,因此被停止。我认为后端脚本可能类似于:Promise.map(this.params.index.split(',')),function(node){return yield client.browseNodeLookup({browseNodeId:this.params.index,})。然后((json)=>{this.body=json;})此外,我还向每个Promise.map添加了{concurrency:500})(