【发布时间】:2021-01-17 01:08:43
【问题描述】:
我正在使用 rest api 服务来访问节点运行程序,我发现 async 和 await 没有保留序列。此代码确实适用于 func 中的第二个 api 调用。我认为 await 和 async 与第二次调用的顺序不一致,这会导致问题。
我在没有第二次 api 调用的情况下使用 func 进行了测试,并且序列很好,所以问题与生成的 CCAPI 承诺有关。我认为“那么”是不正确的。此外,访问慈善 API 的 func 中的代码是独立工作的,因此实际的代码确实有效,并且也在整个代码中运行,但不按顺序运行。
任何帮助表示赞赏。
async function checkCharityAPI(searchTerm) {
const args = { APIKey: myAPIKey, strSearch: searchTerm };
ccAPI.GetCharitiesByName(args).then(function(result) {
var charityResult = JSON.stringify(result);
var charityResultJson = JSON.parse(charityResult);
console.log(charityResultJson["GetCharitiesByNameResult"]);
return charityResultJson;
}).catch(function(err) {
console.log(`Call to ${err.operationName} failed with error: ${err.err}`);
return null;
});
}
app.post("/api/checkcharitytest", asyncHandler(async (req, res, next) => {
var charitySearch = req.body.charitysearch;
console.log("start api call")
var charityResult = await checkCharityAPI(charitySearch);
console.log("end api call")
res.json({ "charityResult": charityResult})
}));
加法-
我也试过这个-
var charitySearch = req.body.charitysearch;
console.log("start api call")
// var charityResult = await checkCharityAPI(charitySearch);
checkCharityAPI(charitySearch).then(function(result) {
console.log("result")
console.log(result);
res.json({ "charityResult": result})
}).catch(function(err) {
console.log(`Call to ${err.operationName} failed with error: ${err.err}`);
});
console.log("end api call")
我还添加了这个 - 然后通过返回值为 null 来更正 seq,尽管它已填充在 func 中 -
async function checkCharityAPI(searchTerm) {
const args = { APIKey: myAPIKey, strSearch: searchTerm };
await ccAPI.GetCharitiesByName(args).then(function(result) {
var charityResult = JSON.stringify(result);
var charityResultJson = JSON.parse(charityResult);
console.log(charityResultJson["GetCharitiesByNameResult"]);
return charityResultJson["GetCharitiesByNameResult"];
}).catch(function(err) {
console.log(`Call to ${err.operationName} failed with error: ${err.err}`);
return null;
});
}
【问题讨论】:
标签: node.js api asynchronous