我有一个Alexa技能,可以获取设备的地址并使用该信息查找附近的设施。
我已经看了@ jfriend00提出的解决方案here。我的回调结构相同。我仍然不明白为什么我的回调在其余代码运行之前没有返回。我应该看到来自console.info()
回调的getJSON()
来电,但它永远不会运行。
编辑:我显然不明白这种异步内容是如何工作的,因为我的日志完全没有问题。有人可以向我解释发生了什么事吗?我查看了我链接的解决方案,我的代码看起来尽可能与他的准系统解决方案相似。我不明白我哪里出错了。
控制台日志
getKaiserBuildingHandler()
const getKaiserBuildingHandler = function() {
console.info("Starting getKaiserBuildingHandler()");
...
switch(addressResponse.statusCode) {
case 200:
console.log("Address successfully retrieved, now responding to user.");
const addressObj = addressResponse.address;
const address = `${addressObj['addressLine1']}, ${addressObj['city']}, ${addressObj['stateOrRegion']} ${addressObj['postalCode']}`;
var ADDRESS_MESSAGE = Messages.ADDRESS_AVAILABLE;
const alexa = this;
getKaiserBuildingHelper(buildingType, address, function(response) {
ADDRESS_MESSAGE += response;
alexa.emit(":tell", ADDRESS_MESSAGE);
console.info("Ending getKaiserBuildingHandler()");
});
break;
...
}
});
...
};

getKaiserBuildingHelper()
const getKaiserBuildingHelper = function(buildingType, address, callback) {
console.info("Starting getKaiserBuildingHelper()");
// var facilityOutput = Messages.ERROR;
var facilityOutput = "Inside building helper function, initial value.";
if (buildingType == BLDG_TYPE.PHARMACY ||
buildingType == BLDG_TYPE.CLINIC ||
buildingType == BLDG_TYPE.HOSPITAL) {
...
facilityOutput = "Before get JSON call.";
getJSON(buildingType, function(err, data) {
if (data != "ERROR") {
console.info("Received data from callback: ", data);
facilityOutput = "The closest Kaiser Permanente " + buildingType + " to your location is located at " + data + ".";
} else {
console.error("Error with data received from callback. ", err);
facilityOutput = "Entered JSON call, returned ERROR.";
}
});
}
...
callback(facilityOutput);
console.info("Ending getKaiserBuildingHelper()");
}

的getJSON()
const getJSON = function(building, callback) {
console.info("Starting getJSON()");
Axios
.get(getFacilitySearchEndpoint(building))
.then(function(response) {
const responseData = response.data.query.search[0].title;
callback(null, responseData);
console.info("Data retrieved from Axios call");
console.info("Ending getJSON()");
})
.catch(function(error) {
callback(error, "ERROR");
console.info("Error caught from Axios call");
console.info("Ending getJSON()");
});
}

getFacilitySearchEndpoint()[维基百科api就像占位符一样]
const getFacilitySearchEndpoint = function(building) {
console.info("Starting getFacilitySearchEndpoint()");
switch (building) {
case BLDG_TYPE.HOSPITAL:
console.info("Ending getFacilitySearchEndpoint() with " + building);
return "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=Albert+Einstein";
break;
case BLDG_TYPE.PHARMACY:
console.info("Ending getFacilitySearchEndpoint() with " + building);
return "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=Harry+Potter";
break;
case BLDG_TYPE.CLINIC:
console.info("Ending getFacilitySearchEndpoint() with " + building);
return "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=Tony+Stark";
break;
default:
console.info("Ending getFacilitySearchEndpoint() with default");
break;
}
console.info("Ending getFacilitySearchEndpoint()");
}

答案 0 :(得分:1)
我在聊天中留下了一些笔记,但事情可能会更清楚。绝对在你提供的链接中再看一下Felix的答案,但是由于你在这里有很多代码,如果我在这种情况下解释的话会更容易理解。
Axios.get
是异步的,这意味着它在 HTTP请求完成之前实际返回。因此,在您发出请求后发生的getJSON
正文中的任何内容实际上都会在调用传递给then
或catch
的函数之前发生:
function getJSON (url, callback) {
Axios
.get(url)
.then(function (data) {
console.log('I happen later, when the request is finished')
callback(null, data)
})
.catch(function (err) {
console.log('I happen later, only if there was an error')
callback(err)
})
console.log('I happen immediately!')
}
很容易混淆 - 在异步代码中,事情不一定按照它们出现在代码中的顺序发生。因此,在调用异步函数时我们必须注意这一点。
这意味着getKaiserBuildingHelper
函数内部存在问题。因为您的getJSON
函数只是Axios promise的回调式包装器,所以它也是异步的。它将在请求完成之前立即返回,并且函数体内的其余代码将继续正常运行。
function getKaiserBuildingHelper (callback) {
let facilityOutput = 'initial value'
getJSON('http://some-url.com', function (err, data) {
console.log('I happen later, when the request is complete')
if (err) {
facilityOutput = 'Error!'
} else {
facilityOutput = 'Success!'
}
})
console.log('I happen immediately!')
callback(facilityOutput)
}
这意味着最后一行callback(facilityOutput)
发生在getJSON
回调之前。结果,facilityOutput
的值保持不变。但是你可以通过移动getJSON
回调中的回调来轻松解决这个问题:
function getKaiserBuildingHelper (callback) {
getJSON('http://some-url.com', function (err, data) {
if (err) {
callback('Error!')
} else {
callback('Success!')
}
})
}
现在您可以按预期使用该功能:
getKaiserBuildingHelper(function (message) {
console.log(message) // => 'Success!' or 'Error!'
}
最后,我不确定您为何已将this.emit
添加到该回调中。这是从别处粘贴的东西吗?