我有一个ajax调用,需要返回一个promise。功能如下
client.tickets.create(ticket, function(err, req, result) { if (err) { logger.error(err); return false; } return JSON.stringify(result); });
在执行下一个动作之前,我必须等待该功能执行。我该如何保证这个功能?
我尝试了以下操作,它给了我一个错误,说Cannot call method then of undefined:
Cannot call method then of undefined
return client.tickets.create(ticket).then(function(result){ return JSON.stringify(result); },function(err){ logger.error(err); return false; });
您有错误,因为create()它不是Promise。承诺异步功能非常容易(如今,nodejs具有内置的Promise支持):
create()
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 });