如何使用回调函数中的异步等待从异步函数中 return 值?

How to return values from async functions using async await from a callback function?

我是 nodejs 的新手,它是回调地狱,我在节点 8 中阅读了关于 async / await 的介绍,并且有兴趣以这种方式实现它

我有一组特定的方法需要以同步方式一个接一个地为 trello 调用 API 例如

  1. 创建图板
  2. 使用看板 ID 创建标签
  3. 使用看板 ID 创建卡片
  4. 给卡片贴上标签
  5. 在卡片中创建列表
  6. 将每个项目添加到卡片列表中

你可以想象在 nodejs 中,这需要大量的回调相互嵌套才能访问前一个对象

createProjectBoard: function (project) {
        t.post("1/board", {
            name: project.name,
            desc: project.description,
            defaultLists: false
        }, function (err, board) {
            if (err) {
                console.log(err);
                throw err;
            }

            //get board id from data
            let boardId = board.id
            let backlogListId = "";
            let highId = "", mediumId = "", lowId = "";

            //create labels
            t.post("1/labels", {
                name: 'High',
                color: 'red',
                idBoard: boardId
            }, function (err, label) {
                console.log(err || 'High label created');
                if (err) return;
                highId = label.id;
            });

            t.post("1/labels", {
                name: 'Medium',
                color: 'orange',
                idBoard: boardId
            }, function (err, label) {
                console.log(err || 'Medium label created');
                if (err) return;
                mediumId = label.id;
            });

            t.post("1/labels", {
                name: 'Low',
                color: 'yellow',
                idBoard: boardId
            }, function (err, label) {
                console.log(err || 'Low label created');
                if (err) return;
                lowId = label.id;
            });

            //create rest of the lists
            t.post("1/lists", { name: "Completed", idBoard: boardId }, function (e, l) {
                if (e) {
                    console.log(e);
                    return;
                }
                console.log(l);
                t.post("1/lists", { name: "Testing", idBoard: boardId }, function (e, l) {
                    if (e) {
                        console.log(e);
                        return;
                    }
                    console.log(l);
                    t.post("1/lists", { name: "In Progress", idBoard: boardId }, function (e, l) {
                        if (e) {
                            console.log(e);
                            return;
                        }
                        console.log(l);

                        //create backlog list
                        t.post("1/lists", { name: "Backlog", idBoard: boardId }, function (e, list) {
                            if (e) {
                                console.log(e);
                                return;
                            }
                            console.log(list);
                            backlogListId = list.id;
                            console.log("backlog card list id:" + backlogListId);

                            _.each(project.userStories, function (story) {
                                //assign labels
                                let labelId = "";
                                switch (story.complexity.toLowerCase()) {
                                    case 'high':
                                        labelId = highId;
                                        break;
                                    case 'medium':
                                        labelId = mediumId;
                                        break;
                                    default:
                                        labelId = lowId;
                                }

                                t.post("1/cards", {
                                    name: story.title,
                                    idLabels: labelId,
                                    idList: backlogListId
                                }, function (e, card) {
                                    if (e) {
                                        console.log(e);
                                        return;
                                    }
                                    let cardId = card.id;
                                    console.log("created id:" + cardId + ";card:" + story.title);                                    

                                    t.post("1/cards/" + cardId + "/checklists", {
                                        name: "Acceptance Criteria"
                                    }, function (e, checklist) {
                                        if (e) {
                                            console.log(e);
                                            return;
                                        }
                                        console.log('checklist created:');
                                        var clId = checklist.id;
                                        _.each(story.criterion, function (criteria) {
                                            t.post("1/cards/" + cardId + "/checklist/" + clId + "/checkItem", {
                                                name: criteria
                                            }, function (e, checkItem) {
                                                if (e) {
                                                    console.log(e);
                                                    return;
                                                }
                                                console.log('created check item:' + checkItem);
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    }

我仍然对上面的代码有问题,其中涉及 __.each 循环,它异步调用循环中的所有函数(重新安排它们最初应该在其中的顺序) - 所以我认为必须有更好的方法来同步调用

我对使用 await / async 清理代码很感兴趣,但是 运行 在从异步回调返回对象时遇到了一些麻烦

解决方案基于sails.js,以下是我正在编写的TrelloService的摘录

考虑以下因素:

 createProjectBoard: async function(project) {
        //get board id from data
        let board;
        let boardId = "";
        let backlogListId = "";
        let highId = "",
            mediumId = "",
            lowId = "";


        try {
            await t.post("1/board", {
                    name: project.name,
                    desc: project.description,
                    defaultLists: false
                },
                function(err, b) {
                    if (err) {
                        console.log(err);
                        throw err;
                    }
                    console.log("board" + b);
                    board = b;
                });

            //create labels
            await t.post("1/labels", {
                name: 'High',
                color: 'red',
                idBoard: board.id
            }, function(err, label) {
                console.log(err || 'High label created');
                if (err) return;
                highId = label.id;
            });

        } catch (err) {
            console.log(err);
        }
}

我需要在标签请求调用中提供板值,尽管我已经设置了等待关键字,但到目前为止我无法检索板对象、事件

我需要能够从回调函数中获取对象并以同步方式将它们用于后续函数调用

我正在使用 trello api 包装器 node-trello 进行调用 (t)

一种方法是将上面的函数包装在更多函数中,如下所示,但我认为这不是最佳实践,因为我必须在我需要的每个对象上编写包装器回调使用

function foo(url,options,cb){
await t.post(url, options,
        function(err, b) {
            if (err) {
                console.log(err);
                throw err;
            }
            console.log("board" + b);
            cb(b);
        });
}

var url = "1/board";
var options = {
            name: project.name,
            desc: project.description,
            defaultLists: false
        };

foo(url,options,function(board){
   console.log(board); //board object
});

欢迎提出任何建议

await 只能在异步函数中使用,它用于等待 Promise 被解决,而不是你想要的。

要稍微清理一下您的代码,请看一下 Promises,但不要指望它会使您的代码看起来不那么难看,您只需将 "callback" 地狱更改为 "then"地狱

I'm interested in using await / async to clean out the code

这有两个步骤:promisification 和 async。您的代码越来越混乱,因为它跳过了第一步。

Promisification 在回调函数周围创建非常简单的返回承诺的包装函数。例如,如果 tTrello class 的实例:

Trello.prototype.postAsync = (url, data) => new Promise((resolve, reject) => {
  this.post(url, data, (err, result) => {
    if (err) { reject(err); }
    else { resolve(result); }
  });
});

第二个步骤是编写您的async/await逻辑,使用承诺返回函数而不是回调。由于它们是承诺返回的,因此它们的代码更加自然:

const board = await t.postAsync("1/board", {
    name: project.name,
    desc: project.description,
    defaultLists: false
});
console.log("board" + board);

//create labels
let highId;
try {
  highId = await t.postAsync("1/labels", {
      name: 'High',
      color: 'red',
      idBoard: board.id
  });
} catch (err) {
  console.log(err || 'High label created');
  return;
}

promisification 步骤繁琐且重复。有一些库可以自动回调到承诺,最著名的是 Bluebird.