如何提升这个功能 - nodejs [duplicate](How to Promisify this function - nodejs [duplicate])
这个问题在这里已经有了答案:
如何将现有的回调API转换为承诺? 17个答案我有一个需要返回承诺的ajax调用。 功能如下
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 :
return client.tickets.create(ticket).then(function(result){ return JSON.stringify(result); },function(err){ logger.error(err); return false; });This question already has an answer here:
How do I convert an existing callback API to promises? 20 answersI have an ajax call which needs to return a promise. The function is as follows
client.tickets.create(ticket, function(err, req, result) { if (err) { logger.error(err); return false; } return JSON.stringify(result); });I have to wait for this function to execute before I can perform the next action. How can I promisify this function ?
I tried the following and it gave me an error saying 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支持):
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 });You have the error because create() is not a Promise. Promisifying an async function is quite easy (nodejs has a built-in Promise support nowadays):
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 });更多推荐
发布评论