我从ProcessSearch中返回了Promise.all,其中包含了更多的Promise。然后,我尝试将更多内容链接到返回的诺言,但这些决定先于返回的诺言。
日志:
Search called
Searching: hello
Searching: hello
Search:https://api.cognitive.microsoft.com/bing/v7.0/search?mkt=en-us&offset=0&q=hello
DatabaseClient: getResults
DatabaseClient: getResults
Results: ******THIS SHOUOLD BE AFTER BELOW***
Number of Results: 9
values: 2
newResults: 9 oldResults: 0 deduplicated: 9
DatabaseClient: saveKeywords: number of keywords:undefined
DatabaseClient: saveResults: number of results:9
DatabaseClient: saveResults resolve
router.post('/search', function(req, res, next){
console.log('Search called');
var body = req.body;
var searchString = body.searchString;
console.log('Searching: ' + searchString);
searchProcessor.ProcessSearch(searchString, databaseClient)
.then(
databaseClient.getResults()
.then( results =>
console.log("Results: " + results)
)
).catch(error => console.log("ERROR: " + error));
})
exports.ProcessSearch = function processSearch(searchString, databaseClient)
{
console.log("Searching: " + searchString);
var searchPromise = searchClient.search(searchString)
.then(results => {
// Add keywords
console.log("Number of Results: " + results.length)
return results;
});
var getSavedResultsPromise = databaseClient.getResults();
return Promise.all([searchPromise, getSavedResultsPromise])
.then( values => {
console.log("values: " + values.length)
var searchResults = values[0];
var savedResults = values[1];
var newResults = deduplicate(searchResults, savedResults, (result) => {return result.url});
var newKeywordsToOccurances = addKeywords(newResults);
databaseClient.saveKeywords(newKeywordsToOccurances);
return databaseClient.saveResults(newResults);
})
}
答案 0 :(得分:0)
解决了我在哪里调用该函数的问题。通过在console.log(results)之前添加结果=>,我猜它会等到执行返回的Promise而不是向前移动。
router.post('/search', function(req, res, next){
console.log('Search called');
var body = req.body;
var searchString = body.searchString;
console.log('Searching: ' + searchString);
searchProcessor.ProcessSearch(searchString, databaseClient)
.then(
databaseClient.getResults()
.then( results =>
console.log("Results: " + results)
)
).catch(error => console.log("ERROR: " + error));
})