gpt4 book ai didi

javascript - 异步工作的生成器函数

转载 作者:行者123 更新时间:2023-11-30 15:20:11 26 4
gpt4 key购买 nike

我想要一个返回一系列东西的 JS 生成器函数,让我们说说它对晚餐的建议。它知道一些菜的名称,但如果我不喜欢它们中的任何一个,它就需要从远程服务器获取更多建议。所以我希望它能工作:

const dishSuggestions = function* (){
yield "pancakes";
yield "pizza";
fetchMealSuggestions().then(suggestions => { // Or even better await.
for (const suggestion of suggestions)
yield suggestion;
});
};

这显然行不通,因为我无法从内部函数中产生。所以我的问题是:如何获得这种行为?我可以吗?或者这是错误的工具?

最佳答案

理论上,在这种情况下您需要的是一个包含异步迭代器的异步生成器。

这是它的样子:

// Note the * after "function"
async function* dishSuggestions() {
yield "pancakes";
yield "pizza";

// async iteration: yield each suggestion, one after the other
for await (const meal of fetchMealSuggestions()) {
yield meal;
}
}

async function logDishes() {
for await (const dish of dishSuggestions()) {
console.log(dish);
}
}

logDishes();

这是一个 working transpilled demo with Babel .

请注意,fetchMealSuggestions 还必须返回异步迭代器才能使异步迭代工作。

话虽这么说,这仍然是每个浏览器刚刚开始提供的全新功能。

More details

现在,看看 question Bergi recommended在评论中。

关于javascript - 异步工作的生成器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43857403/

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