据我了解,我正在调用一个同步函数“ httpGet”,该函数应该返回一个promise。该功能似乎正在工作,因为它已成功通过console.log语句从Airtable中获取了我的所有数据,但是我在.then()方法中得到了任何响应。
在这里我称之为“ httpGet”函数:
async handle(handlerInput) {
let speechText = '';
console.log('Going to fetch Airtable data');
await httpGet(base).then((response) => {
console.log('have promise')
}).catch((err) => {
//set an optional error message here
console.log('do not have promise')
//speechText = 'there is an error ' + err.message;
});
speechText = `Container ID ` + contID + ` is a ` + bincolor + `, ` + gallons + ` located in ` + binloc ;
console.log('speechText = ' + speechText);
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.withSimpleCard('Warehouse Inventory', speechText)
.getResponse();
};
这是被调用的httpGet函数:
async function httpGet(options) {
// return new pending promise
return new Promise((resolve, reject) => {
base('Bins').select({
// Selecting a record in Grid view:
maxRecords: 1,
view: "Grid view"
}).eachPage(function page(records, fetchNextPage) {
// This function (`page`) will get called for each page of records.
records.forEach(function(record) {
console.log('Container ID: ', record.get('Container ID'));
console.log('Gallons: ', record.get('Gallons'));
console.log('Bin Color: ', record.get('Color'));
console.log('Location: ', record.get('Location'));
console.log('Imperfections: ', record.get('Imperfections'));
var contID = record.get('Container ID');
var gallons = record.get('Gallons');
var bincolor = record.get('Color');
var binloc = record.get('Location');
var imper = record.get('Imperfections');
});
// To fetch the next page of records, call `fetchNextPage`.
// If there are more records, `page` will get called again.
// If there are no more records, `done` will get called.
fetchNextPage();
}, function done(err) {
if (err) {
console.error(err); return;
}
});
});
}
最终,我试图获取存储在变量contID,加仑,bincolor,binloc和imper中的值。我该如何完成?
答案 0 :(得分:1)
在httpGet()
中,执行resolve({ contID, gallons, /* ... */ })
,然后在then((response) => {})
中,您的response
将成为带有contID
,gallons
等的对象。属性。请查看this blog post,以获取有关异步返回值的更多详细信息。
答案 1 :(得分:1)
您的代码有太多嵌套,这是一种不好的做法。您无法从诺言中返回值,因为它是异步的,您可以在其中执行您想做的事情。
Factory