我搜索了 ES6 生成器的真实案例,但没有找到正确的解释。我试图理解第一个Promise场景。
假设我们有 2 个剩余 api:getUser 和 getUserComments
我们不想创建避免嵌套then回调功能的线性代码结构。所以...
定义模拟 API
function getUser () {
return new Promise(function(resolve, reject) {
return setTimeout(function() { resolve({id: 1, label: 'John'}); }, 200);
});
}
function getUserComments(userId) {
return new Promise(function(resolve, reject) {
return setTimeout(function() {resolve({comments: 'comments', userId: userId}); }, 200);
});
}
定义生成器
function* generator () {
yield getUser();
yield getUserComments(userId); // userId represents data from first request / first yield how should I pass it ?!
}
var g = generator();
var first = g.next(1);
var second = g.next(2);
如何从第一个yield (yield getUser()) 获取响应并将其传递给下一个yield (yield getUserComments(userId)) ?
最佳答案
您可以将生成的结果分配给变量:
The next() method also accepts a value which can be used to modify the internal state of the generator. A value passed to next() will be treated as the result of the last yield expression that paused the generator. (From MDN, Advanced generators)
既然你正在处理 Promises,那么使用 async/await 将其解包为值是有意义的。
试试这个(我稍微修正了 setTimeout 参数):
async function getUser() {
return new Promise(function(resolve, reject) {
setTimeout(resolve, 0, {
id: 1,
label: 'John'
})
})
};
async function getUserComments(user) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, 0, {
...user,
comments: 'comments',
}, 'userComments');
});
}
function* generator () {
const user = yield getUser();
yield getUserComments(user);
}
(async function () {
const g = generator();
const user = await g.next().value
const comments = await g.next(user).value
console.log(comments)
})()
关于javascript - ES6生成器中如何将第一个yield的值传递到下一个yield?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49252333/