【发布时间】:2019-08-18 10:59:46
【问题描述】:
获取一些记录并发出 POST 命令发送出去,我能够在日志中看到正确的记录 ID,因此逻辑工作。只是不知道如何检索这些值,我尝试过 async/await 并获得未解决的承诺响应并按原样运行返回未定义。异步新手,非常感谢任何帮助!
const axios = require('axios');
exports.handler = (event, context, callback) => {
async function getJobId() {
var jobId
axios({
method: 'get',
headers: {'<Api-Key>': '<my-api-key-value>'},
url: 'https://api.my-website.com/v1/jobs',
params: { jobNumber: event.jobNumber }
})
.then((res) => {
var i,j,x;
for (i in res.data) {
for (j in res.data[i]){
x = res.data[i][j];
jobId = x.id;
}
}
console.log('jobId:',jobId);
return jobId;
})
.catch(function (error) {
console.log('getJobIdError');
console.log(error);
});
}
function getMaterialId() {
var materialId;
axios({
method: 'get',
headers: {'<Api-Key>': '<my-api-key-value>'},
url: 'https://api.my-website.com/v1/materials',
})
.then((res) => {
var i,j,x;
for (i in res.data) {
for (j in res.data[i]){
x = res.data[i][j];
if(x.primaryVendor.vendorPart == event.material){
materialId = x.id;
}
}
}
console.log('materialId:',materialId);
return materialId;
})
.catch(function (error) {
console.log('getMaterialIdError');
console.log(error);
});
}
function getTechId() {
var techId;
axios({
method: 'get',
headers: {'<Api-Key>': '<my-api-key-value>'},
url: 'https://api.my-website.com/v1/technicians',
})
.then((res) => {
var i,j,x;
var fn = event.firstName;
var ln = event.lastName;
var fullName = fn.trim() + ' ' + ln.trim();
for (i in res.data) {
for (j in res.data[i]){
x = res.data[i][j];
if(x.name == fullName){
techId = x.id;
}
}
}
console.log('techId:', techId);
return techId;
})
.catch(function (error) {
console.log('getTechId');
console.log(error);
});
}
function allIds() {
axios.all([
getMaterialId(),
getJobId(),
getTechId()
]);
}
allIds();
};
在输出日志中,我得到了正确的记录 ID:
回应: 空
请求 ID:"50972993-4971-4dcc-b577-0f253f3f3571"
功能日志:
START RequestId:50972993-4971-4dcc-b577-0f253f3f3571 版本:$LATEST 2019-08-17T21:51:51.192Z 50972993-4971-4dcc-b577-0f253f3f3571 技术 ID:1025 2019-08-17T21:51:51.233Z 50972993-4971-4dcc-b577-0f253f3f3571 材料 ID:1725 2019-08-17T21:51:51.432Z 50972993-4971-4dcc-b577-0f253f3f3571 jobId: 37399080 结束请求 ID:50972993-4971-4dcc-b577-0f253f3f3571 报告请求 ID:50972993-4971-4dcc-b577-0f253f3f3571 持续时间:1148.69 毫秒计费持续时间:1200 毫秒内存大小:128 MB 使用的最大内存:65 MB
【问题讨论】:
-
您不能从回调中返回值。请改用回调。
-
那么它只返回三个中的第一个。
标签: asynchronous axios