我正在尝试使用 Bluebird Promises 构建和返回一个对象。Promise 是一个 HTTP 请求,它获取要添加到对象的附加数据。
我创建了一个在 for 循环中执行请求的函数(我也在使用一个执行一些中间件的框架 - 这就是它的意义z.
所在)
const getWebAppCustomFieldDetails = (z, url) => {
const responsePromise = z.request({
url:url,
headers:{
'content-type': 'application/json'
}
});
return responsePromise
.then(response =>{
return JSON.parse(response.content);
});
};
此函数在以下代码中调用:
const webAppFields = (z, bundle) => {
//This section carries creates an initial request which gets the bulk of the data
const responsePromise = z.request({
url: webAppUrl(bundle) + '/' + encodeURI(bundle.inputData.webApp),
headers:{
'content-type': 'application/json'
},
});
//This is an array to hold the objects created from the response
var fields = [];
return responsePromise
.then(response => {
response = JSON.parse(response.content);
//From the response, append the core fields
response.systemFields.forEach( function (systemField) {
fields.push({
'key': systemField.name,
'required': systemField.required,
'type': systemField.type.toLowerCase()
});
});
return response;
})
.then(response => {
//Sometimes there are custom fields that need to be retrieved individually
const customFieldCount = response.fields.length;
var customFieldAppend = '';
for (var i = 0; i < customFieldCount; i++){
getWebAppCustomFieldDetails(z, response.fields[0].links[0].uri)
.then(response =>{
customFieldAppend = {
'key': response.name,
'required': response.required,
'type': response.type.toLowerCase()
};
//This push doesn't updated the fields array!
fields.push(customFieldAppend);
});
}
//This return does not include the custom fields!
return fields;
});
};
我不知道如何从嵌套的 Promise 返回值