ES6asynchronous/等待在课堂上

我试图创build一个类,将发送一个请求(login),保存cookie和使用该cookie进行其他操作,如下载文件。

我创build了一个本地服务器,它将接收一个带有用户名和密码的post方法,一个名为/download的路由器只在用户login时才被访问,否则会返回you need to log in

问题:这是我class的原型(之前):

 const request = require('request-promise-native') class ImageDownloader { constructor(username = null, password = null) { this.username = username this.password = password this.cookie = request.jar() this.init() } init() { // login and get the cookie } download() { // needs the cookie } query() { // needs the cookie } } 

正如你可以在上面的代码中看到的,我需要两个操作的cookie downloadquery所以我虽然关于创build一个init方法,将执行初始操作,如login,并在构造函数中调用它,所以它将被初始化把cookie放在variablesthis.cookie到处使用,但它不起作用,似乎是每隔一个方法调用init

 const request = require('request-promise-native') class ImageDownloader { constructor(username = null, password = null) { this.username = username this.password = password this.cookie = request.jar() this.init() } async init() { await request({ uri: 'http://localhost/login', jar: this.cookie, method: 'post', formData: { 'username': 'admin', 'password': 'admin' } }).catch(e => console.error(e)) } async download() { await request({ uri: 'http://localhost/download/image.jpg', jar: this.cookie }) .then(b => console.log(b)) .catch(e => console.error(e)) } query() { // ... } } const downloader = new ImageDownloader downloader.download() 

它返回给我,我需要login(服务器响应) …但它工作,如果我这样做的变化:

 async download() { await init() // <<<<<<<<<<<< await request({ uri: 'http://localhost/download/image.jpg', jar: this.cookie }) .then(b => console.log(b)) .catch(e => console.error(e)) } 

只有在download方法中调用init时才有效。

如果我把console.log(this.cookie) download它将返回一个空的CookieJar ,如果我把它放在init它会返回正确的cookie,但它会出现在执行下载之后甚至在调用之前调用它的构造函数download

如何解决? 非常感谢你。

@编辑

我做了@ agm1984@Jaromanda X告诉我的变化,但它仍然无效:(

 const request = require('request-promise-native') class ImageDownloader { constructor(username = null, password = null) { this.username = username this.password = password this.cookie = request.jar() this.init().catch(e => console.error(e)) } async init() { return await request({ uri: 'http://localhost/login', jar: this.cookie, method: 'post', formData: { 'username': 'admin', 'password': 'admin' } }) } async download() { return await request({ uri: 'http://localhost/download/image.jpg', jar: this.cookie }) } query() { // ... } } const downloader = new ImageDownloader downloader.download() .then(b => console.log(b)) .catch(e => console.error(e)) 

但是,然后再次…除非我在内部download调用init不起作用。

asynchronous函数返回承诺。 我真的不明白你在做什么,但我知道你只是在打电话

 const downloader = new ImageDownloader downloader.download() 

尝试改变:

 const downloader = new ImageDownloader downloader.download() .then((data) => { // you can use the data here console.log(data) }) 

每次你链接一个。 then()到你的下载方法,它只是增加更多的function到承诺链。 它不会改变下载承诺后来如何使用。

以这个例子为例:

  const doSomething = async () => { return 'something' } async function test() { await doSomething() } test().then((data) => console.log(data))