Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从异步函数返回值并将结果传递给另一个函数_Javascript - Fatal编程技术网

Javascript 从异步函数返回值并将结果传递给另一个函数

Javascript 从异步函数返回值并将结果传递给另一个函数,javascript,Javascript,我用一个类来做一些数据库的事情。在本例中,我希望重置数据并返回数据 export default class Db { constructor () { this.connection = monk('localhost:27017/db') } async resetDB () { const Content = this.connection.get('content') await Content.remove({}) await create

我用一个类来做一些数据库的事情。在本例中,我希望重置数据并返回数据

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' })
  }
}
在我的测试中,我调用了
db.resetDB()
,但我需要获取返回值,因为我需要将ID作为参数传递。 但是我该怎么做呢?我认为我的问题是,这是异步的

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', () => {
    // ...
  })
})

调用异步函数时,它返回一个承诺。因此,您可以在promise的.then()中获得返回值。你可以这样做

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', () => {
    // ...
  })
})

您可以使用done()回调使before函数等待所有异步调用完成

你能做的就是

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', () => {
    // ...
  })
})

您在测试中将回调传递给
resetDB
,但在实际代码中不使用它
resetDB
是一个在代码中没有参数的异步函数您发布的
resetDB
函数是一个
async函数
,它返回承诺,不接受回调?!你是说
db.resetDB()。然后(res=>{…
)?你应该使用
await db.resetDB()
,就像调用任何其他异步函数一样。您可能应该返回该承诺链,以便在钩子实际等待解析之前的
,并且测试以正确的顺序获取数据。我确实收到错误
未处理PromisejectionWarning:未处理的承诺拒绝(拒绝id:1):TypeError:done不是一个函数
@user3142695忘记前面的注释由于某种原因我无法编辑它。但我认为问题在于before回调,它应该是beforeach而不是before。