我试图用不同的URL调用getPromise函数来返回不同的promise,但是在second promise的then success函数中没有定义。
var http=require('http');
var URL='http://localhost:3000';
var getPromise=function(url){
var promise=new Promise(function(resolve,reject){
http.get(url,function(response){
if(response.statusCode < 200 || response.statusCode > 299){
reject(new Error('ErrorCode '+response.statusCode))
}
var result="";
response.on('data',function(chunk){result +=chunk;} )
response.on('end',function(){resolve(result);} )
})
});
return promise;
}
getPromise(URL+'/olympic/2016/ranking/4')
.then(function(data){
console.log("Response "+JSON.parse(data).Country);
getPromise(URL+'/iso/country/'+JSON.parse(data).Country);
})
.then(function(data){
console.log("Data "+data)
})
.catch(function(err){
console.log(err)
});发布于 2017-06-01 14:10:53
确保从promise then返回数据
getPromise(URL+'/olympic/2016/ranking/4')
.then(function(data){
console.log("Response "+JSON.parse(data).Country);
return getPromise(URL+'/iso/country/'+JSON.parse(data).Country);
})
.then(function(data){
console.log("Data "+data)
})
.catch(function(err){
console.log(err)
});无论您从then回调返回什么,都将沿着promise链向下传递。现在您没有返回任何内容,因此隐式返回undefined。
发布于 2017-06-01 14:10:51
你必须为下一个'then‘返回数据才能接收它。
getPromise(URL+'/olympic/2016/ranking/4')
.then(function(data){
console.log("Response "+JSON.parse(data).Country);
return getPromise(URL+'/iso/country/'+JSON.parse(data).Country);
})
.then(function(data){
console.log("Data "+data)
})
.catch(function(err){
console.log(err)
});发布于 2017-06-01 14:10:53
您可以更改函数
getPromise(URL+'/olympic/2016/ranking/4')
.then(function(data){
console.log("Response "+JSON.parse(data).Country);
getPromise(URL+'/iso/country/'+JSON.parse(data).Country)
.then(function(data){
console.log("Data "+data)
});
})
.catch(function(err){
console.log(err)
});https://stackoverflow.com/questions/44299678
复制相似问题