如何提升这个功能

这个问题在这里已经有了答案:

  • 如何将现有的回调API转换为承诺? 17个答案

  • 你有错误,因为create()不是一个Promise。 宣布一个异步函数非常简单(nodejs现在有一个内置的Promise支持):

    function createTicket(ticket) {
        // 1 - Create a new Promise
        return new Promise(function (resolve, reject) {
            // 2 - Copy-paste your code inside this function
            client.tickets.create(ticket, function (err, req, result) {
                // 3 - in your async function's callback
                // replace return by reject (for the errors) and resolve (for the results)
                if (err) {
                    reject(err);
                } else {
                    resolve(JSON.stringify(result));
                }
            });
        });
    }
    
    // 4 - consume your promise with then() (resolved promise) and catch (rejected promise)
    createTicket(ticket).then(function (result) {
        // deal with result here
    }).catch(function (err) {
        // deal with error here
    });
    

    而不是手动将异步代码封装到承诺中,我会建议使用像Bluebird这样的库为您做这件事:

    var Bluebird = require('bluebird');
    
    //either 
    client.tickets = Bluebird.promisifyAll(client.tickets);
    //or 
    client.tickets.createAsync = Bluebird.promisify(client.tickets.create);
    ...
        return client.tickets.createAsync(ticket)
          .then(JSON.stringify)
          .catch(err => {
            logger.error(error); 
            return false
          });
    

    function createTicket(){
    var deferred = Q.defer()
    client.tickets.create(ticket,  function(err, req, result) {
         if (err) { 
                    logger.error(err);
                    return deferred.reject(err)
                }
       return deferred.resolve(result)
    });
    }
    
    createTicket().then(function(){
        //success here
    }, function(){
        //failure here
    });
    

    使用Q api你可以达到承诺。

    链接地址: http://www.djcxy.com/p/55511.html

    上一篇: How to Promisify this function

    下一篇: How to make a promise from setTimeout