gpt4 book ai didi

javascript - 如何将我的 javascript 回调流程转换为 Promise?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:59:50 26 4
gpt4 key购买 nike

function getMentionedUsers(str, next){
var array = getUsernamesFromString(str); //['john','alex','jess'];
if(array.length > 0){
var users = [];
var pending = array.length;
array.forEach(function(username){
getUserByUsername(username).then(function(model){
users.push(model.key);
--pending || next(users); //this is a callback model
});
});
}
};

function getUserByUsername(username){
return admin.database().ref('/users').orderByChild('username').equalTo(username).once('value').then(function(snapshot) {
return snapshot.val(); //this is the firebase example of a promise
});
};

现在,我正在这样做:

    getMentionedUsers(model.body, function(users){
console.log("Mentions", users);
});

但是,我想将 getMentionedUsers 变成一个 promise 。我怎样才能做到这一点?我是 Promises 的新手

最佳答案

你可以使用 Promise.allArray#map:

function getMentionedUsers(str) {
return Promise.all(getUsernamesFromString(str).map((username) => {
return getUserByUsername(username).then((model) => model.key);
}));
}

一个更易读的版本分为两个函数:

function getUserKeyByUsername(username) {
return getUserByUsername(username).then((user) => user.key);
}

function getMentionedUsers(str) {
const promises = getUsernamesFromString(str).map(getUserKeyByUsername);
return Promise.all(promises);
}

关于javascript - 如何将我的 javascript 回调流程转换为 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42963412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com