在异步方法函数中调用方法函数

时间:2019-10-17 11:31:26

标签: vuejs2 nativescript nativescript-vue

我有两种方法: method_1aysnc method_2; 我想在method_1内部调用aysnc method_2(在检索到一些数据之后);

({aysnc method_2捕获数据并将其传递到method_1并执行它。)

我在this.method_1内使用aysnc method_2来调用它,但是什么也没发生。

method_1 (data) {
    console.log( 'I need it here', data );
} ,

triggerByUser () {

    this.method_1( 'just a test' );

    async function method_2 () {

        let code = await fileRetriever( 'songs' );
        console.log( 'this code retrieved: ' ,  code );
        this.method_1( code );
        console.log( 'the code has been sent!' );

    } ;

    method_2 (  ) ;
},

结果:

JS: 'I need it here' 'just a test'
JS: 'response From fileRetriever:' 58
JS: 'this code retrieved: ' 58

(项目是使用NativeScript + Vue编写的)

3 个答案:

答案 0 :(得分:0)

似乎我需要将其作为回调传递;

triggerByUser () {

    this.method_1( 'just a test' );

    async function method_2 ( callback ) {

        let code = await fileRetriever( 'songs' );
        console.log( 'this code retrieved: ' ,  code );
        callback( code );
        console.log( 'the code has been sent!' );

    } ;

    method_2 ( this.method_1 ) ;
},

结果:

JS: 'I need it here' 'just a test'
JS: 'response From fileRetriever:' 58
JS: 'this code retrieved: ' 58
JS: 'I need it here' 58
JS: 'the code has been sent!'

有没有更好的方法?! (因为使用 async +回调对我来说似乎有点肮脏)

答案 1 :(得分:0)

我不了解Nativescript,但是从介绍中可以看出,Vue组件与经典 Vue相同。

如果将method_2嵌套在triggerByUser内,则将其移到methods之外,并使用await正确调用所有功能

methods:{
    method_1 (data) {
      console.log( 'I need it here', data );
    },
    async triggerByUser () {
        this.method_1( 'just a test' );
        await this.method_2();
    },
    async method_2 () {

        let code = await fileRetriever( 'songs' );
        console.log( 'this code retrieved: ' ,  code );
        this.method_1( code );
        console.log( 'the code has been sent!' );

    }    
}

答案 2 :(得分:0)

非常简单。

创建两个方法并在第三个异步方法中调用它们

例如,当用户单击锚标记时,您必须运行两个ajax调用,然后您将像这样进行操作。

<template>
    <div>
         <a @click="getDataFromTwoOtherMethods()">Click here</a>
    </div>
</template>
<script>
    export default{
    ...
    methods:{
       method1(){},
       method2(){},


       async getDataFromTwoOtherMethods(){
            await this.method1();
            this.method2();
            //this method will wait for method1 to execute 
            //and get response and then call second method
       } 
   },
</script>