我正在尝试在 JS 中将多个异步请求链接在一起。基本上,我想从 LastFM API 检索艺术家信息,然后使用该信息查找他们的热门轨道。
到目前为止,我可以成功获取艺术家信息,将其返回,并在下一步中打印出该信息。但是,一旦我尝试对顶级轨道执行第二个请求,正文就不会被打印,并且会立即进入下一步。
我已经尝试了此代码与不同类型的请求的许多不同组合,但我没有得到任何运气。我只想成功执行请求 1(如果成功),然后由其他人按照正确的顺序跟进。
var artistInfo = {
method: 'GET',
url: 'http://localhost:3000/users/db/artistInfo/' + artistName
};
var topTracks = { method: 'GET',
url: 'http://localhost:3000/users/db/topTracks/' + artistName
};
/* Dependencies */
var Promise = require('bluebird');
var reqP = Promise.promisifyAll(require('request-promise'));
reqP(artistInfo)
.then(function(info) {
console.log("got here 1");
return info;
})
.then(function(artist) {
console.log(artist);
reqP(topTracks)
.then(function(body) {
console.log(body);
console.log("got here 2");
return body;
});
return 'test';
})
.then(function(content) {
console.log(content);
return 'test2';
})
.catch(function(err) {
throw err;
});
最佳答案
要对这两个请求进行排序并让外部 .then()
等待这两个请求,您需要返回内部 Promise(.then()
内部的 Promise) handler) 以便链接它们。如果您不返回它们,则没有任何内容链接到父 promise ,因此父 promise 不会等待子 promise 。请参阅我将 return
添加到 return reqP(topTracks)
的行:
var artistInfo = {
method: 'GET',
url: 'http://localhost:3000/users/db/artistInfo/' + artistName
};
var topTracks = { method: 'GET',
url: 'http://localhost:3000/users/db/topTracks/' + artistName
};
/* Dependencies */
var Promise = require('bluebird');
var reqP = Promise.promisifyAll(require('request-promise'));
reqP(artistInfo)
.then(function(info) {
console.log("got here 1");
return info;
})
.then(function(artist) {
console.log(artist);
// *** add return here ***
return reqP(topTracks)
.then(function(body) {
console.log(body);
console.log("got here 2");
return body;
});
})
.then(function(content) {
console.log(content);
return 'test2';
})
.catch(function(err) {
throw err;
});
<小时/>
仅供引用,您的两个请求看起来并不相互依赖,因此您也可以并行执行它们:
var artistInfo = {
method: 'GET',
url: 'http://localhost:3000/users/db/artistInfo/' + artistName
};
var topTracks = { method: 'GET',
url: 'http://localhost:3000/users/db/topTracks/' + artistName
};
/* Dependencies */
var Promise = require('bluebird');
var reqP = Promise.promisifyAll(require('request-promise'));
Promise.all([reqP(artistInfo), reqP(topTracks)]).then(function(results){
// results[0] is artist
// results[1] is tracks
}, function(err){
// error here
});
关于javascript - 多个 Promise 请求在 Javascript 中链接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36612701/