不知道为什么我总是对propertyAnagrams变量不明确,将不胜感激!
const anagramica = require('anagramica');
const processBody = async (generatedString, arrayOfWords) => {
const possibleAnagrams = await anagramica.all(generatedString, (err, response) => {
if (err) {
console.log(`Could not find possible anagrams : ${err}`);
}
else {
console.log("1", response.all);
/// [ Array ] ///
const array = response.all;
console.log("2", array);
/// [ Array ] ///
return array;
}
})
console.log("3", possibleAnagrams)
/// undefined ///
return { possibleAnagrams, arrayOfWords }
}
答案 0 :(得分:2)
anagramica
似乎没有返回Promise。如果您想使用async / await,请考虑将其转换为Promise。
const anagramica = require('anagramica');
const anagramicaPromise = generatedString => new Promise((res, rej) => {
anagramica.all(generatedString, (err, response) => {
if (err) {
return rej(err);
}
res(response);
}
});
const processBody = async (generatedString, arrayOfWords) => {
try {
const possibleAnagrams = await anagramicaPromise(generatedString);
console.log("3", possibleAnagrams);
return { possibleAnagrams, arrayOfWords }
} catch(err) {
console.log(`Could not find possible anagrams : ${err}`);
}
}
答案 1 :(得分:0)
与@Nick相同,但使用es6-promisify
模块:
const { promisify } = require('es6-promisify');
const anagramica = require('anagramica');
const processBody = async (generatedString, arrayOfWords) => {
try {
const { all: possibleAnagrams } = await promisify(anagramica.all)(generatedString);
return { possibleAnagrams, arrayOfWords };
} catch (err) {
console.log(`Could not find possible anagrams : ${err}`);
}
};