我正在尝试在我的节点应用程序中创建两个异步承诺,以便在从外部API获取时返回所有最新的部署日期。我之前没有承诺这样做,但是我无法将所有最新的DeploymentDate都返回到映射数组,因为它超出了范围。因此,我遵循谷歌上发现的JavaScript promises教程,但是我没有成功实现它。请在下面找到代码和堆栈跟踪:
const express = require('express')();
const request = require('request');
const moment = require('moment');
const ta = require('time-ago')();
var promise = require('promise')()
const webApplications = require('./account.json');
var newArr = new Array();
express.listen(3001, function() {
console.log('Server is listening...');
express.get('/data', function(req, res) {
res.json(webApplications.map((item, latestDeploymentDate) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', true);
// return 'foo';
const newRelicRequest = {
url: `https://XXX`,
headers: {
'X-Api-Key': 'XXX'
}
}
const gitlabRequest = {
url: `XXX`,
headers: {
'PRIVATE-TOKEN': 'XXX'
}
}
var promise = new Promise(function(resolve, reject) {
request(newRelicRequest,(err, resp, body) => {
const data = JSON.parse(body);
const latestDeployment = data.deployments[0];
latestDeploymentDate = new Date(latestDeployment.timestamp);
console.log(new Date(latestDeployment.timestamp));
resolve(body);
});
var secondaryPromise = new Promise(function(resolve, reject) {
request(gitlabRequest, (err, resp, body) => {
const gitlabData = JSON.parse(body);
const currentTag = latestDeployment.description;
var currentIndex;
console.log(`${item.appName}` + ' ');
console.log(`Last deployed: ${latestDeployment.description}
on ${moment(latestDeploymentDate).format('YYYY-MM-DD')}`);
gitlabData.find((item, index) => {
currentIndex = index;
return item.name == currentTag
});
if (currentIndex > 3) {
console.log(`This ${currentIndex} was released ${ta.ago(latestDeploymentDate)}`);
resolve(latestDeploymentDate);
} else {
${ta.ago(latestDeploymentDate)}`);
console.log(`This ${currentIndex} was released ${ta.ago(latestDeploymentDate)}`);
resolve(latestDeploymentDate);
}
})
})
promise.then(function(result){
console.log(result)
})
});
}));
});
})
答案 0 :(得分:0)
当您想以可预测的顺序执行另一个承诺时,您希望将它们链接起来:
promise()
|-----------------|
secondarypromise(promiseResult)
|------------------|
finalHandler(secondayPromiseResult)
|------------------|
在您的代码中,您可以这样做:
promise()
.then(secondaryPromise)
.then(finalHandler);
注意:我发现您使用的request
不支持Promises。我可以推荐request-promise
- 这样您只需要一个库用于API调用。 request-promise
就像request
一样,但它基于Promises API实现了所有内容。