在代码中有一个promise.then试图被用来设置一个全局变量originalUrl,但是originalUrl没有被改变。任何帮助将不胜感激。
我的应用程序.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
开心每一天1111
相关分类