问:我了解如何在 请求 内返回承诺,但是如何在另一个请求内的 要求中返回新承诺 ?
我的代码:
request({ // --------------request 1------------
url: request_data.url,
method: request_data.method,
form: request_data.data,
headers: oauth.toHeader(oauth.authorize(request_data, token))
}, function (err, res, body) {
body = JSON.parse(body);
var count = 0;
for (var i = 0; i < body.items.length; i++) {
if (body.items[i].name.toLowerCase().indexOf(params.name.toLowerCase()) >= 0) {
ids[count] = body.items[i].id;
count++;
}
}
return new Promise((resolve, reject) => {
request({ **request 2** ------------request 2--------------
url: request_data2.url,
method: request_data2.method,
form: request_data2.data,
headers: oauth.toHeader(oauth.authorize(request_data2, token))
}, function (err2, res2, body2) {
body2 = JSON.parse(body2);
var counts = 0;
var ret = {};
//console.log(ids[0]);
for (var i = 0; i < body2.items.length; i++) {
//console.log(body2.items[i].name);
for (var y = 0; y < body2.items[i].custom_attributes.length; y++) {
if (body2.items[i].custom_attributes[y].attribute_code == 'category_ids') {
if (ids[0] == body2.items[i].custom_attributes[y].value) {
ret[counts] = body2.items[i].name;
counts++;
}
}
}
} //------- resolve / reject ----------
if (err) {
reject({
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
});
} else {
resolve({
body: JSON.parse(ret),
})
}
});
});
});
当我只有一个请求时,输出有效。但是,当请求中有另一个请求时,当我尝试调用此函数时,会收到一个空输出{} 。
答案 0 :(得分:0)
首先,停止在非承诺回调中执行操作。除了解决承诺外,您不应在“请求内”做任何事情:
function requestAsync(data, headers) {
return new Promise((resolve, reject) => {
request({
url: data.url,
method: data.method,
form: data.data,
headers,
}, function (err, res, body) {
if (err) reject(err); // don't ignore errors!
else resolve(body);
});
});
}
现在,您可以将业务代码放入then
回调中,并且从then
回调中,您还可以return
其他承诺来建立一个链:
const oauthHeaders = oauth.toHeader(oauth.authorize(request_data, token);
return requestAsync(request_data, oauthHeaders).then(JSON.parse).then(body => { /*
^^^^^^ */
const ids = [];
var count = 0;
for (var i = 0; i < body.items.length; i++) {
if (body.items[i].name.toLowerCase().indexOf(params.name.toLowerCase()) >= 0) {
ids[count] = body.items[i].id;
count++;
}
}
return requestAsync(request_data2, oauthHeaders).then(JSON.parse).then(body2 => {
// ^^^^^^
var counts = 0;
var ret = {};
//console.log(ids[0]);
for (var i = 0; i < body2.items.length; i++) {
//console.log(body2.items[i].name);
for (var y = 0; y < body2.items[i].custom_attributes.length; y++) {
if (body2.items[i].custom_attributes[y].attribute_code == 'category_ids') {
if (ids[0] == body2.items[i].custom_attributes[y].value) {
ret[counts] = body2.items[i].name;
counts++;
}
}
}
}
return {
// ^^^^^^
body: JSON.stringify(ret), // I don't think you meant `parse` here
};
});
}).catch(err => {
return { // I don't think you want to `throw` this object
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
};
});