1 回答
TA贡献1946条经验 获得超4个赞
将请求回调函数括在异步函数中,以便它等待成功响应或错误,然后再继续。
const request = require('request');
const objectToPreserve = ['someName1', 'someName2'];
/**
Async function which would return the response or throw an error from
request endpoint
*/
const requestAsync = async(options) => {
request(options, function(error, response) {
if (error) {
throw new Error(error);
}
return response;
});
};
/**
Main function
*/
const execute = async() => {
const options = {
'method': 'GET',
'url': baseUrl + '/childObject' + urlParam + '&parentObejctid=' + parentObjectId,
'headers': {
'Authorization': token
}
};
const response = await requestAsync(options);
const childObjects = JSON.parse(response.body);
for (const i of childObjects) {
const name = i.name;
const childObjectId = i.id;
if (objectToPreserve.indexOf(name) > -1) {
console.log(name, ' preserved')
} else {
const deleteOptions = {
'method': 'DELETE',
'url': baseUrl + '/childObject' + urlParam + '&id=' + childObjectId,
'headers': {
'Authorization': token
}
};
const deleteResponse = await requestAsync(deleteOptions);
console.log(JSON.parse(deleteResponse.statusCode));
}
}
}
// Execute main function
await execute();
我建议你使用 const 和 let 而不是 var 来表示变量声明,并且还使用另一个库(如 axios)而不是请求,因为请求已被弃用。
添加回答
举报
