gpt4 book ai didi

javascript - NodeJS 中使用 bluebird Promise 的链函数

转载 作者:行者123 更新时间:2023-12-03 05:12:03 24 4
gpt4 key购买 nike

我很抱歉又问了一个 Promise 问题,但是,我不太明白它,在阅读了这里的大量问题和解释后,我仍然在挣扎。

因此,在我的 Nodejs 项目中,我尝试做三件事。

1)从 Facebook API 获取用户信息

graph.get(message.user, function getUserInfo(err, res) {
console.log(res)
}

2)从另一个 API 获取用户列表

request.get('https://api-url/api/users', {
'auth': {
'bearer': 'bearerAuth'
}
})

3) 检查 Facebook 用户的姓名与我从 API 返回的 JSON 数据中的姓名是否匹配,然后将其交给用户。

let aPieceOfData = "";

Bluebird.promisifyAll(graph.get(message.user))
.then(function(res) {
// this should give me the response from the Facebook API which is the user
// Then pass the response to the next .then(function(){})
})
.then(function(res) {
request.get('https://api-url/api/users', {
'auth': {
'bearer': 'bearerAuth'
}
const apiData = JSON.parse(response.body);
for (i in apiData) {
if (res.username == apiData[i].username) {
// if the username matches the user name then save some data to a variable outside this scope so I can access it
aPieceOfData = apiData[i].item;
}
}
})
})
.catch(function(err) {
console.log(err, "<<<<<<<");
})

格式可能有点不对。但我很难理解 Promise 是如何工作的,以及如何在链接函数之间传递数据,而不是最后将其保存在函数之外,以便我可以使用它。

有人可以给出一些解释和/或一些对初学者友好的解释的链接。

最佳答案

基于示例from the doc

var fs = Promise.promisifyAll(require("fs"));

fs.readFileAsync("myfile.js", "utf8").then(function(contents) {
console.log(contents); }).catch(function(e) {
console.error(e.stack); });

我认为应该是这样的:

var g = Bluebird.promisifyAll(graph);
g.getAsync(message.user)
.then(function (res) {
// this should give me the response from the Facebook API which is the user
// Then pass the response to the next .then(function(){})
return res;
})
.then(function (res) {
return request.get('https://api-url/api/users', {
'auth': {
'bearer': 'bearerAuth'
}
});
})
.then(function (response) {
const apiData = JSON.parse(response.body);
for (i in apiData) {
if (res.username == apiData[i].username) {
// if the username matches the user name then save some data to a variable outside this scope so I can access it
aPieceOfData = apiData[i].item;
}
}
})
.catch(function (err) {
console.log(err, "<<<<<<<");
});

关于javascript - NodeJS 中使用 bluebird Promise 的链函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767422/

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