gpt4 book ai didi

javascript - 带有 async wait es6 函数的变量未定义

转载 作者:行者123 更新时间:2023-12-01 00:24:35 26 4
gpt4 key购买 nike

不知道为什么我一直在 possibleAnagrams 变量上未定义,任何帮助将不胜感激!

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 }
}

最佳答案

看起来 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}`);
}
}

关于javascript - 带有 async wait es6 函数的变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com