Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/407.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.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 Vue exports.function语法_Javascript_Vue.js_Vue Component - Fatal编程技术网

Javascript Vue exports.function语法

Javascript Vue exports.function语法,javascript,vue.js,vue-component,Javascript,Vue.js,Vue Component,我在一个单独的文件中有这样一个函数 exports.getScore = (storeId) => { var getScore = new Promise(function (resolve, reject) { let data = this.getScore('day', storeId) data.then(function (result) { resolve(result) }) }) let result await get

我在一个单独的文件中有这样一个函数

exports.getScore = (storeId) => {
  var getScore = new Promise(function (resolve, reject) {
    let data = this.getScore('day', storeId)
    data.then(function (result) {
      resolve(result)
    })
  })
  let result
  await getScore.then(function (data) {
    result = data
  })
  return result
}
有人能帮我理解语法吗?这样我就可以进行异步运行,然后执行我的等待调用?
提前谢谢

对于您的问题,您只需要在函数之前放置一个
async

exports.getScore = async (storeId) => { /* snip */ }
但实际上,您的代码中存在一些问题
首先,你可以在承诺执行人的决心中通过承诺

new Promise(resolve => {
  // This will work
  resolve(anotherPromise)
})
但是,如果您已经有了承诺,您可以直接退还
如果您想确定这是一个本地承诺,或者您不确定这是否是一个承诺。
Promise.resolve将其包装起来

Promise.resolve(anotherPromiseOrValue)
因此,您的代码可以更改为:

exports.getScore = (storeId) => this.getScore('day', storeId)
它还等于:

exports.getScore = this.getScore.bind(this, 'day')
但是还有一个问题:这里的
这个
是什么?
如果从Vue方法中提取此函数,则
this
可能是Vue实例。
那么我恐怕上面的代码不会像您预期的那样工作。
所以我建议您在组件的生命周期挂钩中使用
getScore
,比如
mounted

例如:

mounted () {
  this.getScore('day', this.storeId).then(score => {
    this.score = score
  })
}
或者使用异步/等待

async mounted () {
  this.score = await this.getScore('day', this.storeId)
}

只需将函数更改为
this.getScore.bind(this'day')
?那么您将如何实现上述功能?:)我在另一个组件中使用这个函数?我只想把它放在一个地方,然后引用它,而不是放在三个地方。但是我不知道用这种方式进行异步的语法好吧,我想我的问题很容易被误解:)但是,我的问题是。我有3个文件。login.vue 2。dashboard.vue 3。函数1。我想通过运行一些get函数来填充我的会话。2.然后我想在我的仪表板上使用这些会话数据。3.我创建了我的函数,所以在我的登录页面上不会有500行api调用,因为它没有真正意义。因此,我在functions.js中有4个函数,因为我不需要任何异步属性。但我想添加最后5个,在这里我将我的承诺转换为JSF中的可用数据,然后只添加一个函数并等待承诺