2017-08-02 69 views
1

我想在Feathersjs上同時運行兩個鉤子,但是由語句「hook.service.find({query:{active:'1'}})調用的」addHost「函數。然後(page => page.data.forEach(addHost));「在第一個鉤子在第二個鉤子之後執行。我需要hook1中的所有語句在啓動hook2之前完成。我做錯了什麼?提前致謝! 我的代碼如下:如何在feathersjs上運行同步鉤子

Hook1:

module.exports = function (options = {}) { 
    return function hook1 (hook) { 
    hook.service.find({ query: { active: '1' } }).then(page => page.data.forEach(addHost)); 
    }; 
}; 

function addHost(client) { 
    /* Some code here.... */ 
    console.log('This code is executing at the end'); 
} 

HOOK2:

module.exports = function (options = {}) { 
    return function hook2 (hook) { 
    /* Some code here.... */ 
    console.log('This code is executing first'); 
    }; 
}; 

xxx.hooks.js文件

module.exports = { 
    /* Some code here.... */ 

    after: { 
    all: [], 
    find: [], 
    get: [], 
    create: [hook1(), hook2()], 
    update: [], 
    patch: [hook1(), hook2()], 
    remove: [] 
    }, 

    /* Some code here.... */ 

}; 

輸出:

此代碼執行第一

此代碼在最後

回答

1

正在執行你不想鉤同步執行,但你想要的異步操作繼續之前完成上。這可以通過在你的情況下返回Promise as documented in the asynchronous hook API docs來完成,如下所示:

module.exports = function (options = {}) { 
    return function hook1 (hook) { 
    return hook.service.find({ query: { active: '1' } }) 
     .then(page => page.data.forEach(addHost)) 
     .then(() => { 
     // Always return the `hook` object or `undefined` 
     return hook; 
     }); 
    }; 
}; 
+0

It works,Thank you Daff,you rocks! –