如何使用promises编写简短的可重用函数?

时间:2016-06-09 10:32:53

标签: javascript promise

在同步代码中编写可重用的单行函数很容易。

像这样:

function bounce(password, error)
{
  if (!passwordChecker.validate(password))
  {
    console.error('bad password');
    database.logError(password);
    error.value = htmlHelper(error5);
    return true;
  }
  return false;
}

您可以轻松地在任何地方重复使用,如下所示:

if (bounce(password, result)) return result.value;
//else continue with the web method...

但是,您究竟是如何使用异步承诺代码执行此操作的?

有没有办法将此代码缩短为一行?我不想每次都复制和粘贴10行:

return new Promise<string>(function (resolve, reject) 
{
    const bouncerError: {value: string} = {value : null};
    self._bouncer.isTokenValid(request, bouncerError)
    .then((isValid) => 
    {
        if (!isValid) 
        {
            resolve(bouncerError.value); 
            throw null; 
        }
        return Promise.resolve();
    })
    .then(() => {
        //continue with the web method
    });

这是可恢复的功能,如果它有助于澄清我的想法:

isTokenValid(request: hapi.Request, jsonErrorResponseString: {value: string})
{
    const self = this;
    return new Promise<boolean>((resolve, reject) =>
    {
        if (!request || !request.headers || !request.headers['token'])
        {
            jsonErrorResponseString.value = responseHelper.getErrorResponse(ResponseErrorCode.invalidToken);
            resolve(false);
            return;
        }

        self._jwtHelper.isJwtValid(request.headers['token'])
        .then(function(isValid: boolean)
        {
            if (!isValid)
            {
                jsonErrorResponseString.value = responseHelper.getErrorResponse(ResponseErrorCode.invalidToken);
                resolve(false);
            }
            resolve(true);
        }
        ,function(error: any)
        {
            jsonErrorResponseString.value = responseHelper.getErrorResponse(ResponseErrorCode.unknownError);
            resolve(false);
        })
    });
}

1 个答案:

答案 0 :(得分:0)

哦,我明白了。我想如果我将外部承诺传递给公共代码,它可以节省空间:

    const isValid = await bouncer.isTokenValid(token);
    if (!isValid) throw new ControlFlowError();

isTokenValid(request: hapi.Request, hapiResolve: any): Promise<boolean>
{
    if (!request || !request.headers || !request.headers['token'])
    {
        hapiResolve(responseHelper.getErrorResponse(ResponseErrorCode.invalidToken));
        return Promise.resolve(false);
    }

    return new Promise<boolean>((resolve, reject)  =>
    {
        this._jwtHelper.isJwtValid(request.headers['token'])
        .then(function(isValid: boolean)
        {
            if (!isValid)
            {
                hapiResolve(responseHelper.getErrorResponse(ResponseErrorCode.invalidToken));
                resolve(false);
            }
            resolve(true);
        }
        ,function(error: any)
        {
            hapiResolve(responseHelper.getErrorResponse(ResponseErrorCode.unknownError));
            resolve(false);
        })
    });
}