首页 > 解决方案 > 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

标签: javascriptnode.jsmongodb

解决方案


在 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

推荐阅读