2016-09-30 55 views
1

我试图使用JavaScript生成器函数从数据库中获取数据。但每一步都取决于之前的数据。我使用了Wes Bos的ES6.io课程中的一个例子,并且它的功能类似于通过JavaScript生成器函数循环使用

function ajax(url) { 
    fetch(url).then(data => data.json()).then(data => dataGen.next(data)) 
} 

function* steps() { 
    console.log('fetching beers'); 
    const beers = yield ajax('http://api.react.beer/v2/search?q=hops&type=beer'); 
    console.log(beers); 

    console.log('fetching user'); 
    const user = yield ajax('https://api.github.com/users/[user]'); 
    console.log(user); 

    console.log('fetching fat joe'); 
    const fatJoe = yield ajax('https://api.discogs.com/artists/51988'); 
    console.log(fatJoe); 
} 

const dataGen = steps(); 
dataGen.next(); // kick it off 

这很好。问题是这取决于全球可用的dataGen。我需要在一个函数中完成所有这些。我怎样才能在一个循环中调用dataGen,但从另一个函数中调用?我在寻找与此类似:

function ajax(url) { 
    fetch(url).then(data => data.json()).then(data => dataGen.next(data)) 
} 

function* steps() { 
    console.log('fetching beers'); 
    const beers = yield ajax('http://api.react.beer/v2/search?q=hops&type=beer'); 
    console.log(beers); 

    console.log('fetching user'); 
    const user = yield ajax('https://api.github.com/users/[user]'); 
    console.log(user); 

    console.log('fetching fat joe'); 
    const fatJoe = yield ajax('https://api.discogs.com/artists/51988'); 
    console.log(fatJoe); 
} 

function getInfo() { 
    const dataGen = steps(); 
    for (const data of dataGen) { 
     console.log(data); 
    } 
} 

getInfo()呼叫理想就能够揭开序幕发生器和能够从每一步传递数据到下一个,从而使数据得到填补正确地输出。

有什么建议吗?我可以使用ES6功能或功能,但没有更高。

下面是因为当我尝试做了第二个选项会发生什么浏览器控制台输出,一个我很想得到工作:

enter image description here

+0

而在某种意义上你的“这样的事情”不工作? –

+0

这不是在'ajax'函数中'dataGen'没有定义,我无法将dataGen传递给''ajax'函数。 – pjlamb12

+0

@Jonasw检查浏览器控制台输出的编辑问题。 – pjlamb12

回答

1

这里最棘手的部分是,AJAX函数不会返回任何内容,如果是,它不会立即返回数据。

因此,要做你正在寻找的东西,我们必须将承诺逻辑移到我们的循环中。我们可以完全摆脱ajax(),只是直接使用抓取:

function* steps() { 
    const beers = yield fetch('http://api.react.beer/v2/search?q=hops&type=beer'); 
    const user = yield fetch('https://api.github.com/users/wesbos'); 
    const fatJoe = yield fetch('https://api.discogs.com/artists/51988'); 
} 

function getInfo() { 
    const dataGen = steps(); 
    for(const promise of dataGen) { 
    promise.then(data => data.json()).then(data => { 
     console.log(data); 
     dataGen.next(data); 
    }); 
    } 
} 

getInfo(); 
+0

谢谢!这应该可以帮助我实现真正的代码! – pjlamb12

+0

是否有一种方法可以在第一个yield中传递数据,但是在这之后每个'.next()'步骤都有新的数据? – pjlamb12