简体   繁体   中英

Return value from asynchronous function and pass result to another function

I'm using a class to do do some database stuff. In this example I want to reset the data and return the data.

export default class Db {
  constructor () {
    this.connection = monk('localhost:27017/db')
  }

  async resetDB () {
    const Content = this.connection.get('content')
    await Content.remove({})
    await createContent()
    return Content.findOne({ title: 'article' })
  }
}

In my test I'm calling the db.resetDB() , but I need to get the returned value, as I need to pass the ID as parameter. But how do I do that? I think my problem is, that this is asynchronous.

let id
describe('Test', () => {
  before(() => {
    db.resetDB(res => {
      id = res._id
      Article.open(id) // How do I get the ID?? I do get undefined here
      Article.title.waitForVisible()
    })
  })

  it('should do something', () => {
    // ...
  })
})

When the async function is called, it returns a Promise. hence you can get the return value in .then() of the promise. You can do it something like this,

let id
describe('Test', () => {
  before(() => {
    db.resetDB().then(res => {
      id = res._id
      Article.open(id) // How do I get the ID?? I do get undefined here
      Article.title.waitForVisible()
    })
  })

  it('should do something', () => {
    // ...
  })
})

You can make the before function to wait until all asynch calls gets finished by using done() callback.

https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

What you can do is

let id
describe('Test', () => {
  before((done) => {
    db.resetDB().then(res => {
      id = res._id
      Article.open(id) // How do I get the ID?? I do get undefined here
      Article.title.waitForVisible()
      done()
    })
  })

  it('should do something', () => {
    // ...
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM