这是我的异步代码片段,它通过提供网站网址正常工作这是一个异步请求我想让这个同步请求 有人能帮我一下吗 我正在使用alchemy api获取提要 我从云端获取数据
var urls = [website ur names]
for(var j=0;j<urls.length;j++){
alchemyapi.feeds("url",urls[j], {}, function(response) {
console.log(response["feeds"]);
for(var i=0;i<response["feeds"].length;i++)
var feed = response["feeds"][i].feed;
getFeed(feed);
console.log("Title: " +objToString(response["feeds"][i]));
});
}
function objToString (obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
var request = require('request');
var getFeed = function(feed){
feeds = encodeURIComponent(feed);
request('http://cloud.example.com/v3/mixes/contents?streamId=feed/'+feeds/, function (error, response, body)
{
if (!error && response.statusCode == 200)
{
console.log(body)
}
else
{
console.log("Error "+response.statusCode)
}
});
}
答案 0 :(得分:0)
var urls = [website ur names]
var request = require('request');
function promiseRequest(feeds){
return new Promise(function(resolve,reject){
request('http://cloud.example.com/v3/mixes/contents?streamId=feed/'+feeds/,
function (error, response, body)
{
if (!error && response.statusCode == 200)
{
resolve(body);
}
else
{
reject(response.statusCode);
}
});
}
}
function getFeedsFromUrls(urls){
return new Promise(function(resolve,reject){
var count=0,totalCount = urls.length;
var result=[];
for(var j=0;j<urls.length;j++){
alchemyapi.feeds("url",urls[j], {}, function(response) {
for(var i=0;i<response["feeds"].length;i++)
var feed = response["feeds"][i].feed;
promiseRequest(feed).then(function(data){
count++;
result.push(data);
if(count>=totalCount){
resolve(result);
}
}).catch(function(err){
count++;
if(count>=totalCount){
resolve(result);
}
});
});
}
});
}
getFeedsFromUrls(urls).then(function(result){
console.log(result);
})