0

I recently started working with nodejs. I'd like to follow the async nature of it and write some helper functions which take one function as an argument and call that function only if certain criteria are met, for example:

function areMandatoryFieldsFilledOut( fields, httpRequest, httpResponse, callback ) {
    /* some logic */
    if( mandatory_fields_have_been_filled_out ) {
        callback();
    } else {
        httpResponse.send('Mandatory fields have not been filled out!');
    }
}
// usage
areMandatoryFieldsFilledOut(['username', 'password'], req, res, function () {
    // this is executed only if both username and password values are supplied
}

What would be the best way write such functions? Is there a special word that You use for the beginning of the function name, like, 'ensure', e.g. 'ensureAuthenticated( callback )?' Is there a way to convince the reader of my code that the callback will be called only if the criteria are met just by function declaration (name and args)?

4

2 回答 2

0

该事物的现有命名法包括connect/的express名称middlewareRuby on Railsa 的名称before_filter。我使用 express 中间件,它具有非常相似的模式,但与stack函数的排序相结合,在这种情况下,我命名这些函数时没有任何特定的约定,除了试图明确它们的作用、检查或要求。

app.post('/submit', signedIn, authorized, formIsValid, function (req, res) { /*...code to process form.../*});

MW如果我想明确说明这是中间件,有时我会在结尾加上parseFormMWor supportedFormatMW

于 2013-07-15T21:10:48.460 回答
0

我认为你看错了。需要澄清的不是函数名称,而是callback参数。我会改用以下函数签名:

checkMandatoryFieldsFilledOut(
        fields,
        httpRequest,
        httpResponse,
        filled_out_callback
)

或者,如果该参数名称感觉太长,我会使用ok_callback. 如有必要,我还会给他们一个可选fail_callback的,以防调用者在条件失败时需要进行一些处理:

checkMandatoryFieldsFilledOut(
        fields,
        httpRequest,
        httpResponse,
        ok_callback,
        fail_callback  /* optional */
)
于 2013-07-16T02:22:17.057 回答