gpt4 book ai didi

javascript - 如何将 "transfer"变量传递到 Node Express 路由器中的 Promise 链?

转载 作者:行者123 更新时间:2023-12-03 07:32:53 27 4
gpt4 key购买 nike

我试图在 promise 链中进行两个单独的数据库调用,尽管出于测试目的,第一个调用被传递的简单字符串替换。

我的问题是我无法在第二个 promise 中访问变量 msg(我尝试设置 context.foo = msg。

router.route("/")
.get(function(request, response) {

var session = request.session;

return new Promise(function(resolve, reject) {

resolve("h!");

}).then(function(msg){

return new Promise(function(resolve, reject) {

Snippet.find({}, function(error, data) {
let context = {
snippets: data.map(function(snippet) {
return {
name: snippet.name,
snippet: snippet.snippet,
createdAt: snippet.createdAt,
user: snippet.user,
id: snippet._id
};
}),
foo: msg
};
resolve(context);
});
});

}).then(function(context){
response.render("start/index", context);
}).catch(function(err){
response.end(err);
});
});

另一次尝试,这里尝试将路由器绑定(bind)到 Promise...

 router.route("/")
.get(function(request, response) {

var session = request.session;

return new Promise(function(resolve, reject) {

resolve("hi!");

}).then(function(msg){

router.msg = msg;

return new Promise(function(resolve, reject) {

Snippet.find({}, function(error, data) {
let context = {
snippets: data.map(function(snippet) {
return {
name: snippet.name,
snippet: snippet.snippet,
createdAt: snippet.createdAt,
user: snippet.user,
id: snippet._id
};
}),
foo: this.msg
};
resolve(context);
}.bind(router));
});

第三次尝试...

router.route("/")
.get(function(request, response) {

var session = request.session;

return new Promise(function(resolve, reject) {

context.msg = "hi!";

resolve(context);

}).then(function(context){

return new Promise(function(resolve, reject) {
Snippet.find({}, function(error, data) {
context.snippets = {
snippets: data.map(function(snippet) {
return {
name: snippet.name,
snippet: snippet.snippet,
createdAt: snippet.createdAt,
user: snippet.user,
id: snippet._id
};
}),
};
resolve(context);
});
});

}).then(function(context){
response.render("start/index", context);
}).catch(function(err){
response.end(err);
});
});

所以基本问题始终是,当我没有周围对象,没有“this”将其附加到 =) 时,如何在 Promise 范围内“注入(inject)”或使用变量

最佳答案

利用bluebird强大的 Promise.coroutine() :

router.route("/")
.get(Promise.coroutine(function*(request, response) {
try {
const dbResult1 = yield getValueFromDatabaseAsync(/* w/e */);
const dbResult2 = yield getValueFromDatabaseAsync(/* w/e, can be dbResult1 */);

const context = {...}; // use dbResult1 and dbResult2 here normally
response.render("start/index", context);
} catch (err) {
response.end(err);
}
}));

关于javascript - 如何将 "transfer"变量传递到 Node Express 路由器中的 Promise 链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35744492/

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