【发布时间】:2021-10-10 10:29:02
【问题描述】:
我正在调用一个 API“getProjectListForInstance”并在响应中获得结果,该响应是一组对象。像这样:
[ { "_id": "uyuyiuyiuy", "project_name": "Project1", }, { "_id": "hjhjhjhjkh", "project_name": "Project2", } ]
return new Promise((resolve, reject) => {
RESTService.getProjectListForInstance(previousInstance)
.then((result) => {
this.copyProjectInfo(result);
});
});
现在使用上面的结果在下面的代码中。
copyProjectInfo(projects) {
console.log('copyProjectInfo');
return new Promise((resolve, reject) => {
RESTService.createProjectInfoForNewInstance(projects)
.then((result) => {
console.log("Successfully done");
console.log(result);
});
});
},
上面的代码不起作用。得到 502 但是当我像下面这样在代码本身中创建一个数组时,它工作正常。
copyProjectInfo(projects) {
console.log('copyProjectInfo');
let details =
[
{
"_id": "uyuyiuyiuy",
"project_name": "Project1",
},
{
"_id": "hjhjhjhjkh",
"project_name": "Project2",
}
];
return new Promise((resolve, reject) => {
RESTService.createProjectInfoForNewInstance(details)
.then((result) => {
console.log("Successfully done");
console.log(result);
});
});
},
在将第一个 API 接收到的对象用作第二个 API 的输入之前,我是否需要转换它?以及如何?
谢谢, 乔蒂
【问题讨论】:
-
您应该删除那些 Promise 构造函数并直接从
RESTService方法返回 Promise。这称为Promise Constructor anti-pattern。确保也使用catch()来处理任何错误。
标签: javascript node.js arrays object