How to ensure correct “this” with Promise.promisify?

后端 未结 2 1206
名媛妹妹
名媛妹妹 2020-12-03 21:46

I am trying to refactory my nodejs server using promises with Bluebird library, but I am stuck in a simple problem.

After to get the users from my db, I want to list

相关标签:
2条回答
  • 2020-12-03 22:17

    This is just the very common problem of calling "unbound" methods.
    You can pass the context as an option to Promise.promisify to have it bound:

    var getNotifications = Promise.promisify(adapter.getNotifications, {context: adapter});
    

    Alternatively, you'd need to .bind() the method, or call the new getNotifications function on the adapter (using .call()). You might also consider using Promise.promisifyAll(adapater) and then just calling adapter.getNotificationsAsync(…).

    Notice that this still doesn't work. You cannot simply create promises in a loop - you need to await them explicitly and return a promise from the then callback, otherwise just the undefined value you returned will be passed to the next callback immediately.

    adapter.getUsers().then(function(users) {
        return Promise.all(users.rows.map(function(item){
            var dbUser = "sigalei/" + item.value.name;
            console.log(dbUser);
            return getNotifications(dbUser);
        }));
    }).then(function(results) {
        for (var i=0; i<results.length; i++)
            console.log("result:", results[i]);
    });
    

    Instead of Promise.all(users.rows.map(…)), in Bluebird you can also use Promise.map(users.rows, …).

    0 讨论(0)
  • 2020-12-03 22:26

    What about simply

    var getNotifications = Promise.promisify(adapter.getNotifications.bind(adapter));
    

    or possibly

    var getNotifications = Promise.promisify(function () {
        return adapter.getNotifications.apply(adapter, arguments);
    });
    

    ?

    I'm not sure I understand your problem well, but this should make sure this is bound and not undefined when you do return getNotifications(dbUser);

    0 讨论(0)
提交回复
热议问题