如何提升这个功能

编程入门 行业动态 更新时间:2024-10-06 08:33:14
如何提升这个功能 - 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 answers

I 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 });

更多推荐

本文发布于:2023-08-07 18:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465224.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!