javascript - Node.js,Mongodb:如何使用`promise.then`设置全局变量?
问题描述
在代码中有一个promise.then
试图用于设置全局变量originalUrl
,但originalUrl
没有被更改。任何帮助将不胜感激。
myApp.js:
// create a mongoose model
var urlSchema = new mongoose.Schema({
original_url: String,
short_url: String
});
urlSchema.plugin(findOrCreate)
var Url = mongoose.model('Url', urlSchema);
let promise = new Promise(function(resolve, reject) {
app.post("/api/shorturl/new", (req, res) => {
// receive an url in the post and return a
// short id. After that, the short id can be used
// to go to the original url.
// Handle the data in the POST request
// get the hostname from the request
originalUrl = req.body.url;
// Create an identifier for the url
shortUrl = md5(originalUrl).toString().slice(-7)
// test to see if the host is live
var url = new URL(originalUrl);
hostname = url.hostname;
// if host is live
dns.lookup(hostname, function (err) {
if (err == undefined){
// if not found, save the original_url and the
// short_url, return
Url.findOrCreate({ original_url: originalUrl, short_url: shortUrl}, (err, result) => {
console.log(result)
res.json({
original_url: originalUrl,
short_url: shortUrl
});
})
}
if (err != undefined){
console.log(">>> error <<<")
res.json({"error":"host down"});
}
});
resolve(originalUrl)
});
})
promise.then(
function(result) { originalUrl = result },
function(error) { /* handle an error */ }
);
console.log(originalUrl) // undefined
解决方案
在 promise 解决之前,传递给的函数中的代码then()
不会运行。所以代替这个:
promise.then(
function(result) { originalUrl = result },
function(error) { /* handle an error */ }
);
console.log(originalUrl)
...你需要做更多这样的事情:
promise.then(
function(result) { originalUrl = result },
function(error) { /* handle an error */ }
).then(
function() { console.log(originalUrl); }
);
这是一个简单的可运行示例,希望能提供有关其工作原理的想法:
var originalUrl = undefined;
var promise = new Promise((resolve, reject) => {
setTimeout( function() {
resolve("http://example.com");
}, 250)
});
promise.then(
function(result) { originalUrl = result },
function(error) { /* handle an error */ }
).then(
function() { console.log('promise resolved: ', originalUrl); }
);
console.log('promise pending: ', originalUrl);
结果:
promise pending: undefined
promise resolved: http://example.com
推荐阅读
- javascript - Blazor wasm 调用 javascript,传递大数组很慢
- android - 为什么 Flutter 中的 BloCListener 不保存状态,认证过程中出现 setState() 问题?
- c# - 表格调整大小时 iitems 之间的 tablelayoutpanel 空间
- javascript - JS 在滚动效果上显示/隐藏标题 - 但仅在标题向上滚动并移出窗口后
- c# - 创建受密码保护的 influxDB
- java - Firebase 存储中的“getBytes()”和“getStream()”方法有什么区别?
- html - 锚标签在 svg foreignObject 内不起作用
- javascript - 为 scrollLeft() 添加 event.data
- c++ - 当 filesystem::path 被破坏时程序崩溃
- ruby-on-rails - Rails6 + Nginx + Passenger + ActionCable = websocket 已关闭