简体   繁体   中英

How to pass a function as parameter to Promise in TypeScript?

When trying to write a wrapper class for asynchronous DynamoDB calling, I failed with the attempt to wrap all the return statements with a function call as:

function composePromise(method: (params: any, callback: (err, res) => void) => void, params: any): Promise<any> {
    return new Promise<any>((resolve, reject) =>
        method(params, (err, res) => {
            if (err) reject(err);
            else resolve(res);
        })
    );
}

create(params: any): Promise<any> {
    return composePromise(this._db.put, params);
}

Which is strange, because after I move the promise in create without any change, it works.

create(params: any): Promise<any> {
    return new Promise<any>((resolve, reject) =>
        this._db.put(params, (err, res) => {
            if (err) reject(err);
            else resolve(res);
        })
    );
}

So I am guessing it might be some closure issue, but cannot figure out why. Could anyone please help me with that?

I think that this._db.put is probably a shortcut to some other function declared on this._db , if so then the method is probably using this and that's where it fails.

You should bind the correct context to that function

create(params: any): Promise<any> {
    return composePromise(this._db.put.bind(this._db), params);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM