njs_promise_then_finally_function(njs_vm_t *vm, njs_value_t *args,
    njs_uint_t nargs, njs_index_t unused)
{
    njs_int_t              ret;
    njs_value_t            value, retval, argument;
    njs_promise_t          *promise;
    njs_function_t         *function;
    njs_native_frame_t     *frame;
    njs_promise_context_t  *context;

    frame = vm->top_frame;
    context = frame->function->context;

    ret = njs_function_call(vm, njs_function(&context->finally),
                            &njs_value_undefined, args, 0, &retval);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    promise = njs_promise_resolve(vm, &context->constructor, &retval);
    if (njs_slow_path(promise == NULL)) {
        return NJS_ERROR;
    }

    njs_set_promise(&value, promise);

    function = njs_promise_create_function(vm, sizeof(njs_value_t));
    if (njs_slow_path(function == NULL)) {
        return NJS_ERROR;
    }

    function->u.native = context->handler;

    *((njs_value_t *) function->context) = *njs_arg(args, nargs, 1);

    njs_set_function(&argument, function);

    return njs_promise_invoke_then(vm, &value, &argument, 1);
}
njs_promise_then_finally_function(njs_vm_t *vm, njs_value_t *args,
    njs_uint_t nargs, njs_index_t unused)
{
    njs_int_t              ret;
    njs_value_t            value, retval, argument;
    njs_promise_t          *promise;
    njs_function_t         *function;
    njs_native_frame_t     *frame;
    njs_promise_context_t  *context;

    frame = vm->top_frame;
    context = frame->function->context;

    ret = njs_function_call(vm, njs_function(&context->finally),
                            &njs_value_undefined, args, 0, &retval);
    if (njs_slow_path(ret != NJS_OK)) {
        return ret;
    }

    promise = njs_promise_resolve(vm, &context->constructor, &retval);
    if (njs_slow_path(promise == NULL)) {
        return NJS_ERROR;
    }

    njs_set_promise(&value, promise);

    function = njs_promise_create_function(vm, sizeof(njs_value_t));
    if (njs_slow_path(function == NULL)) {
        return NJS_ERROR;
    }

    function->u.native = context->handler;

    *((njs_value_t *) function->context) = *njs_arg(args, nargs, 1);

    njs_set_function(&argument, function);

    return njs_promise_invoke_then(vm, &value, &argument, 1);
}